pjs.httpRequest()
This API was added in Profound.js 6.1.0. This API replaces pjs.sendRequest(), which is now deprecated.
API Overview
The pjs.httpRequest() API is used to send requests to web services.
Parameters
Object options/String requestType
If you pass a string, you can pass the request type (get, post). If you set this parameter as an object, it will be passed into the underlying HTTP request module. You do not need to pass any other parameters should you use an object as the first parameter. You may also set alwaysReadBody: true in this object to allow documents (such as JSON documents) to be received even when the HTTP status code would normally indicate an error. Please see below for other possible options.String URL
The endpoint to your web service.String|Object Body (optional)
The body of the request. If you pass in an object, it will send the request in JSON and it will also return JSON. Otherwise, it will pass as text and return a String.
Return Value
Object / String The response body.
Exception Handling
This API will throw an exception if the HTTP request couldn't be completed (such as for a networking problem), or if the HTTP request completes with a status code of 400 or higher. You may prevent throwing errors for status codes 400 or higher by setting the alwaysReadBody option (see above.)
Examples
Example of General Use
//Simple
var result = pjs.httpRequest("post", "http://website.com/myJSONAPI", {key: 'value'});
//Advanced, using request API options
result = pjs.httpRequest({
method: "POST",
uri: "http://website.com/myJSONAPI",
body: {key: 'value'},
json: true,
timeout: 5000,
time: true
});
httpRequest object parameter options
The following can be used:
method (String): This could be any of GET, POST, DELETE, PUT.
url | uri (String): URL of the endpoint. It could be an absolute or relative path.
body (String|Object): Entity body for POST and PUT requests. Must be a Buffer, String or FormData. If the json option is true, then body must be a JSON-serializable object.
headers (Object):
common request header options e.g., User-agent, Content-Type, Accept, Accept-Encoding, etc.
auth (Object): Basic HTTP authentication option
'user' or 'username'
'pass' or 'password'
timeout (Integer): Integer value in milliseconds for setting connection timeout. If not defined, the default timeout value is 10000ms (10 seconds).
As of PJS 7.6.0, a server configuration option, httpRequestAPITimeout, can be set to override the default timeout for requests that do not specify the “timeout” parameter.
statusCode (Boolean): (default: false) Allows the API call to store the response's status code into an object responseStatus from the sent request object. You may find this info detailed under the "Using the statusCode and responseHeaders parameters" section below. (This feature is available in PJS versions 6.6.0 and newer.)
responseHeaders (Boolean): (default: false) Allows the API call to store the response's headers into an object responseHeaders from the sent request object. You may find this info detailed under the "Using the statusCode and responseHeaders parameters" section below. (This feature is available in PJS versions 6.6.0 and newer.)
json (Boolean): If true, then request body is set to JSON representation of value and adds Content-type: application/json header. The response body is also parsed as JSON.
gzip (Boolean): (default: false) request compressed content encoding from server
followRedirect (Boolean): (default: true) follow HTTP 3xx responses as redirects
maxRedirects (Integer): (default: 15) maximum redirects to follow if followRedirect is set to true
localAddress (String): IP Address for setting the Local Interface from which the request should be emitted.
encoding (String): (default: ‘utf8’) – if null, response body will be returned as a Node.js Buffer
cert: Public x509 certificate to use.
key: Private key in PEM format.
ca: An authority certificate or array of authority certificates to check the remote host against.
passphrase (String): A string of passphrase for the private key.
strictSSL (Boolean): Set to false to disable SSL certificate verification. Note: Disabling SSL certificate verification could lead to the request/response data being intercepted and unencrypted by an attacker. This option can be used for development/testing, but should never be used with real data. To allow verification of certificates issued by your own certificate authority, use the ca option.
proxy (String): Forwards request through HTTP(s) proxy.
alwaysReadBody (Boolean): The default behaviour of pjs.httpRequest is to interpret the response as an error if the remote API returns an HTTP status code >= 400, in which case response body data is not passed to the Profound.js program. Instead, an error is thrown. Some APIs return useful information back in the response body even when then response code is >= 400. To read the body even when the response code is >= 400, supply the "alwaysReadBody" property to the argument object.
allowGetBody (Boolean): (default true) Set this to true to allow sending body for the GET method.
time (Boolean): If true, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:
timingStart: Timestamp of the start of the request (in Unix Epoch milliseconds).
timings: Contains event timestamps in millisecond resolution relative to timingStart. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
socket: Starts when the socket is connected. Resets when new data is transferred.
lookup: Starts when a socket is assigned. Ends when the hostname has been resolved.
connect: Starts when lookup completes. Ends when the socket is fully connected.
response: Starts when request has been flushed. Ends when the headers are received.
end: Relative timestamp when the last bytes of the response are received.
timingPhases: Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain
wait: Duration of socket initialization (timings.socket)
dns: Duration of DNS lookup (timings.lookup - timings.socket)
tcp: Duration of TCP connection (timings.connect - timings.socket)
firstByte: Duration of HTTP server response (timings.response - timings.connect)
download: Duration of HTTP download (timings.end - timings.response)
total: Duration of entire HTTP round-trip (timings.end)
Using the statusCode and responseHeaders parameters:
When enabling the statusCode and responseHeaders options, the resulting data is stored into the request object instead of the response. This is to prevent overwriting any response object parameters that the API response may send.
To do this, it is advised to use a variable for reference to the request object compared to instantiating a request object directly into the call, to be able to retrieve the resulting status code and response headers from their own parameters:
EXAMPLE:
Request API with statusCode and responseHeaders enabled
//Create the request object
let _requestObject = {
method: "POST",
uri: "http://website.com/myJSONAPI",
body: {key: 'value'},
json: true,
timeout: 5000,
time: true,
statusCode: true,
responseHeaders: true
};
//send the requestObject via httpRequest
result = pjs.httpRequest(_requestObject);
//retrieve the status code via "responseStatus" and the headers via "responseHeaders"
let status = _requestObject.responseStatus;
let headers = _requestObject.responseHeaders;
Note: the statusCode and responseHeaders properties are available in PJS versions 6.6.0 and newer.
Some documentation pages have recently moved to a new section: Profound AppDev. If you are having trouble finding specific pages, try the documentation search capability or reach out to our Support team!