api

Calls a REST API and returns the response. Use api for anything reachable over HTTP: your own services, public APIs, or a vendor's endpoints.

Fields

Either profile or url must be given. A profile is an API profile from the configuration. The profile carries the base URL, the headers sent on every call, and the connection pool to use. Headers and parameters set on the command are added to the profile's headers and parameters.

FieldTypeDefaultDescription
onErrorcommand blockCommands to run if this command raises an uncaught error.
profileprofile nameAPI profile from the configuration. Either this or 'url' must be specified.
urldynamic stringURL of the API. Either this or 'profile' must be specified. With a profile, this must be a relative path, which is added to the end of the profile's URL, and the profile's addPath decides whether a path may or must be added.
method"GET" | "POST" | "PUT" | "DELETE"Defaults to POST when a body is given and GET otherwise.
headersobject of string → dynamic stringHeaders for the call, typically used for authorization. Use secret(...) for credentials or API keys. With a profile, these are merged with the profile's headers: a header the profile already sets can only be changed when that header allows it, and a new header can only be added when the profile allows headers to be added.
queryParamsobject of string → dynamic stringQuery parameters added to the URL. With a profile, these are merged with the profile's query parameters: one the profile already sets can only be changed when that parameter allows it, and a new one can only be added when the profile allows query parameters to be added.
bodydynamic dictThe JSON body of the request.
timeoutdynamic string or integerTimeout for this call, in seconds.

Result

The response body is the command's result, available as result in the next command. A JSON response is parsed into a Python object. A text response is returned as a string, and a binary response as bytes. An empty body returns the HTTP status code as a number. The command does not check the status code. A timeout or a connection failure raises an error, which onError can catch.

Example

Look up the caller's location, then the hourly forecast
"api": {
  "url": "https://api.ip2location.io",
  "queryParams": {
    "ip": "{ result }",
    "key": "{ sys.secret['IP2LOCATION_KEY'] }"
  }
},
"var": {
  "location": "{ result }"
},
"api.forecast": {
  "url": "{ f'https://api.weather.gov/points/{location['latitude']},{location['longitude']}' }"
}

Rules

  • Only GET, POST, PUT and DELETE are supported.
  • Credentials are best kept out of the definition. Read them with sys.secret[...] in a header, or put them in the API profile.
  • Timeouts default to the connection pool's settings. timeout overrides the default for this call.