Using the HTTP API
The HTTP API provides functionality to perform various of different HTTP related queries.
Basic usage of the API:
const response = context.httpAPI()
.newRequestBuilder()
.get('https://service')
.build()
.perform();
if (response.succeeded()) {
const data = response.bodyText();
}
Example how to use the HTTP API to POST a JSON structure including adding custom request headers.
const theObject = {};
const response = context.httpAPI()
.newRequestBuilder()
.url('https://service')
.method('POST')
.header('A Header', 'Some Value')
.authorization('Bearer ABCDEF') // Same as setting the header 'Authorization' to the value
.acceptsJson() // Same as setting the header 'Accept' to 'application/json'
.jsonBody(JSON.stringify(theObject))
.build()
.perform();
if (response.succeeded()) {
const data = response.bodyText();
}
If you have some common endpoints often called, these could be declared as destinations within the Administration UI. Each destination is given a unique name that you refer to from the code. The benefits to use destinations are:
-
Less code in the configuration
-
The definition of the endpoint is declared in one place only.
-
Easy to update and adopt to changes
-
-
Authorization details can be configured instead of expressed in code
-
You can override or configure the request further on in the code.
-
For example many services uses the same base URL and authentication but there are variations in the URL and/or in the request data passed.
-
context.httpAPI()
.newRequestBuilder('the-name-of-your-destination')
// configure request more..
.build()
.perform();
Read more about named destinations here.
URL Builder / Path Variables
Using the URL builder to construct URLs:
const response = context.httpAPI()
.newRequestBuilder()
.url() // urlbuilder
.base('https://service/test/${ID}/something/${TYPE}')
.replacePathVariables({ 'ID' : '1234', 'TYPE' : 'Item'})
.param('param1', 'value1')
.and() // complete urlbuilder
.build()
.perform();