Skip to main content

$http.config

This method configures the default HTTP client settings.

tip

When you make frequent requests to the same external resource or with the same configuration, use this method to avoid repeating them on every call to $http.query. Also this method allows you to enable HTTP response caching.

Syntax

The method accepts an object with the following properties:

PropertyTypeDescription
urlObjectBase URL settings. You need to specify all nested properties: protocol, host, and port.
tip
After you have configured the base URL, you can use relative URLs when calling $http.query.
url.protocolStringBase URL protocol. Possible values: http and https.
url.hostStringBase URL host.
url.portNumberBase URL port. This is usually 80 or 443 for HTTP and HTTPS respectively.
timeoutNumberRequest timeout in milliseconds. Cannot exceed 25000.
authHeaderStringThe value of the Authorization header to be sent with every request.
cacheTimeToLiveInSecondsNumberTime in seconds during which responses to successful HTTP requests with the cachingRequired parameter will be cached.
caution
If the script doesn’t contain a call to $http.config with this property, response caching will be disabled.
oauth2ResourceDetailObjectOAuth 2.0 authorization settings.
$http.config({
url: {
protocol: "https",
host: "example.com",
port: 443
},
timeout: 10000,
authHeader: "Bearer " + $secrets.get("EXAMPLE_COM_BEARER_TOKEN"),
cacheTimeToLiveInSeconds: 3600
})

How to use

In the following example, the OpenWeather API URL is set as the base URL, and HTTP response caching is enabled with a TTL of 10 minutes. This allows reducing the quota usage when making repeated weather forecast requests for the same city.

Where to configure the default settings

Most often, $http.config is called either in the start state, which the bot switches to at the beginning of the conversation, or in the init tag.

require: city/cityEn.sc
module = sys.zb-common

init:
$http.config({
url: {
protocol: "https",
host: "api.openweathermap.org",
port: 443
},
cacheTimeToLiveInSeconds: 600
});

theme: /

state: CurrentWeather
q!: * air temperature [in] $City *
script:
$temp.response = $http.get("/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${appid}&units=${units}", {
query: {
lat: $parseTree._City.lat,
lon: $parseTree._City.lon,
appid: $secrets.get("OPENWEATHER_API_KEY"),
units: "imperial"
},
cachingRequired: true
});
if: $temp.response.isOk
a: Right now it’s {{Math.floor($temp.response.data.main.temp)}} °F in {{$parseTree._City.name}}.
else:
a: I couldn’t fetch the weather forecast. Please try again.