Use request method to place secure HTTP calls

Request method is a secure mechanism to send HTTP requests from an app to a third-party domain, without exposing any sensitive information that is part of the request. Through browsers, app users may intercept sensitive information such as API keys or user credentials. Request method safeguards against such exposure. Typically, HTTP requests are routed through proxy servers. In such cases, sending the HTTP requests through the request method helps identify the origin in scenarios where the third-party domain has enabled Cross Origin Resource Sharing (CORS) support.

Note:This Request Method is supported only on FDK version 9.0.0 or later and platform version 2.3. If you are on platform version 2.2 (scheduled for deprecation on December, 2023) and building an app that uses the Request Method, see Request Method with domain whitelisting.

To use the request method,

  1. As part of the app configuration, configure request templates.
  2. In manifest.json, declare the template(s) that the app code uses.
  3. From the app logic, invoke the configured template(s), and make HTTP requests to third-party domains.

For a demonstration of this feature, see our collection of sample apps with the request method.

Notes:
  • The default request timeout is five seconds. For the local testing of apps that use the request method, you can specify an appropriate timeout. For information on local testing with REQUEST_TIMEOUT, see Test apps that use request method.
  • The rate limit for requests is 50 requests per minute per app per account.
  • In the requests.json file, you can configure a maximum of 100 templates.

Allow-list IPs

At times, API/resource providers do not want apps to connect to their APIs/resources, unless the app is trying to connect from a known and approved system/org. To get the origin (from where the requests originate) approved, the app devs will have to provide the list of IPs from which the requests can originate. The resource providers will allow-list these IPs in their system and allow any request that comes from these IPs to access their resources. If you want to access such a resource, you will have to provide the following IPs to the resource providers, for allow-listing.

For custom app devsIf you are building an app for Freshchat and if IP whitelisting is enabled for your Freshchat account, allow-list the following IPs to enable your app to access the Freshchat resources.

RegionIPs
United States18.233.117.211 and 35.168.222.30
Europe-Central18.197.138.225 and 52.57.69.21
India13.232.159.149 and 13.233.170.242
Australia13.211.182.225 and 52.63.187.64

Note:If you are on platform version 2.2 (scheduled for deprecation on December, 2023) and migrating an app that uses the Request Method with domain whitelisting: If your app was accessing restricted resources with IPs being allow-listed, your request call would have had the staticIP option set to true. With this latest Request Method, you need not set the staticIP option. It is auto-enabled when accessing restricted resources.

Configure request templates

Request templates are snapshots of all the HTTP requests that an app is expected to make.

  1. From the app’s root directory, navigate to the config folder and create a requests.json file (if requests.json does not exist).
  2. In requests.json, use the following syntax to configure all request templates that the app is expected to use, as JSON objects.

Attributes of the request.json file

  • <requestTemplateName>object

    <requestTemplateName> is the name used at runtime to invoke the request template. This object contains the attributes that are required to build the request.

Template substitutions

Template substitutions enable the usage of variables in the <requestTemplateName>.schema attributes. During runtime, depending on where the variables are used, they can be populated by:

Variable limitations

Variables can be used only in the following <requestTemplateName>.schema attributes. Also, the type of data that can populate the variables varies depending on the attribute in which the variables are used.

<requestTemplateName>.schema attributesType of data that can populate the variables
Note:For a detailed description of these schema attributes, see the <requestTemplateName>.
host
  • Non-secure iparam values
  • Contextual data
path
  • Non-secure iparam values
  • Contextual data
headers (can be used only in <header-value>)
  • Non-secure iparam values
  • Secure iparam values
  • Stored access tokens
  • Contextual data
query
  • Non-secure iparam values
  • Contextual data

Substitute template variables with iparam values

Use the following syntax to declare a template variable that is populated with iparam values at runtime.

<%= iparam.validIparamName %>

variableName must match the context variable name used in the runtime API when invoking the request template. If there is a mismatch in the names, the runtime API call fails.

encode() This function enables encoding secure iparams that are passed as part of the request.

SyntaxExample
<%= encode(iparam.validIparamName) %>"Authorization": "Bearer <%= encode(iparam.api_key) +':x'>"

Substitute template variables with contextual data

Use the following syntax to declare a template variable that is populated with contextual data, passed through the runtime API that invokes the request template.

<%= context.variableName %>

Substitute template variables with access tokens

Use the following syntax to declare a template variable that is populated with an access token value.

<%= access_token %>

Note:This variable is used only in <requestTemplateName>.schema.headers.<header_value> to facilitate the app to place an OAuth request call. This variable should be used when <requestTemplateName>.options.isOAuth is true.

Declare templates

From templates configured in the config/requests.json, in manifest.json, declare the ones that the app code uses, for a specific product.

  1. From the app’s root directory, navigate to the manifest.json file.
  2. Under product.<productName>, use the sample shown in the right pane and create a requests attribute.

Invoke templates

To send an HTTP request to a third-party domain, in the app code, include the invokeTemplate() method. This method serves as a runtime API call. As part of the call, the app can pass a dynamic context and any other data that the template requires.

  1. In the front-end HTML files (such as iparams.html), include the client JS resource as follows: <script src="{{{appclient}}}"></script> Note:If your existing app uses Request method with domain whitelisting and if you are migrating your app to use the templated request method, in the front-end HTML files (such as iparams.html), replace the existing client JS resource (<script src="https://static.freshdev.io/fdk/2.0/assets/fresh_client.js"></script>) with <script src="{{{appclient}}}"></script>
  2. Navigate to the app.js file and use the syntax in the right pane to include the invokeTemplate() method.

Arguments of invokeTemplate()

  • requestTemplateName string Mandatory
    Identifier of the request template in config/requests.json and the request in manifest.json. The requestTemplateName must be the same in the app code, configuration (config/requests.json), and declaration (manifest.json).

  • An object with the following optional attributes:

    • contextobject

      All contextual data that the template requires, specified as key-value pairs of <variableName>:<variableValue>. <variableName> must be the same as that used in config/requests.json to receive contextual data.

    • bodyobject

      Request body.

      Response caching: Requests made through the request method are governed by rate limits. To prevent repetitive calls from breaching the rate limits, the request method comes with an opt-in response caching feature, for front-end apps. The cache and ttl options available as part of the invokeTemplate() method, enable browsers to cache the responses that are retrieved from third-party calls. The responses are cached in the Browser’s local storage. For requests that haven’t changed since the last call, the response is retrieved from the cache. This conserves the app’s rate limits as the number of requests made to the third-party are conserved.

Response

If the runtime API call results in placing a successful request call to the third-party domain, a data object similar to the following sample is returned.

{
"status" : 200,
"headers":
  {
    "Content-Length": 20,
    "Content-Type": "application/json;charset=utf-8"
  },
"response": '{ "Name": "Rachel"}'
}
  • status number

    HTTP status code.

  • headers object

    Additional context about the response, received as an object of valid <headerParameterName>:<headerParameterValue> pairs.

  • response string

    Data retrieved successfully from the third-party domain, through the request method, specified as a string.

Test apps that use request method

In the local testing of apps that use the Request Method to make third-party HTTP requests, you can specify a value for the request timeout.

To configure the request timeout to a suitable value, perform one of the following:

  • Use the REQUEST_TIMEOUT parameter along with the fdk run command as follows:
    SyntaxExample
    REQUEST_TIMEOUT=<timeout in milliseconds> fdk runREQUEST_TIMEOUT=10000 fdk run
  • Navigate to the .env file and add the following:
    SyntaxExample
    export REQUEST_TIMEOUT=<timeout in milliseconds>export REQUEST_TIMEOUT=10000
Important:
  • Minimum value for REQUEST_TIMEOUT: 5000
  • Maximum value for REQUEST_TIMEOUT: 10000
  • If you specify a REQUEST_TIMEOUT value that breaches the min or max limits, the timeout is defaulted to the min or max value and a warning message is displayed.
  • If you don’t specify a value for REQUEST_TIMEOUT, the timeout value is 5 seconds.

For information on how to test an app that uses the Request method feature, see Test your App.

Request Method with domain whitelisting

Important:This request method is supported only for building apps with platform version 2.2 and FDK versions prior to 9.0.0. Support for building apps on platform version 2.2 is scheduled for deprecation on December, 2023. Ensure to migrate to the latest platform and FDK versions. If you are on the latest FDK version (platform 2.3), to build apps that use the request method, see Request Method.

In this request method, the hosts to which the apps are expected to make request calls are whitelisted in manifest.json. The other attributes such as methods, paths, query parameters, header parameters, options, and request body are dynamically generated during runtime.

Notes:
  • The default request timeout is five seconds. For the local testing of apps that use the request method, you can specify an appropriate timeout. For information on local testing with REQUEST_TIMEOUT, see Test apps that use request method.
  • The rate limit for requests is 50 requests per minute per app per account.

Usage

The request method should be defined in the app.js for front-end apps or in the server.js for the serverless apps.

The following table lists the parameters and their description.

ParameterDescription
URLIs mandatory to make the Request method call.
optionsIs a JSON object and can include the following properties:
  • headers: HTTP Headers.
  • body: Entity body, applicable for PATCH, POST, and PUT requests. Should be a string.
  • staticIP: A boolean value used to make requests with a static outgoing IP.
  • maxAttempts: The maximum number of times a request will try to retrieve a response if a network or 429/5xx HTTP error occurs. The maximum permissible value for this argument is 5.
  • retryDelay: The delay between retry requests, specified in milliseconds. The maximum permissible value for this argument is 1500 ms.
dataData received from the Request method if the request is successful.
errorData received from the request if an error is encountered.

Using iparams

Iparams can be used in requests as part of the following:

  • Header

  • URL
    https://passport-office.com/user?id=<%= iparam.passport %>

  • Body

    client.request.post("https://api.freshchat.com/v2/users", {
        headers: {
            Authorization: "Bearer <%= encode(iparam.freshchatApiToken) %>"
        },
        body: JSON.stringify({
            "email": "govind.patel@freshworks.com",
            "avatar": {
                "url": "https://web.freshchat.com/img/johndoe.png"
            },
            "phone": "123456789",
            "properties": [{
                "name": "orderId",
                "value": "#1242"
            }],
            "first_name": "Govind",
            "last_name": "Patel"
        })
    });

    Note:Secure iparams can only be used in the request header. If secure iparams are present in the request body or URL, the fdk run command displays an error message Secure iparam cannot be used in request body or URL.

Sample Requests

Note:For API requests that require authentication, you may need to encode the auth header in base64 format.

var headers = {"Authorization": "Basic <%= encode(iparam.api_key) %>"};
var options = { headers: headers, body: "Hello world"};
var url = "https://sample.crm.com/contacts.json";
client.request.post(url, options)
  .then (
    function(data) {
      console.log(data);
    },
    function(error) {
      console.log(error);
  });

OAuth Request

For information on how to make an OAuth request, see Usage in the OAuth section.

Test

For information on how to test an app that uses the Request method feature, see Test apps that use request method.

Errors

In case of request failure, a status code is displayed along with a message to help troubleshoot the issue.

The following table lists all the supported status codes.

Status codeDescription
400Is returned due to invalid input. For example, if you are making a request to a domain that has not been whitelisted or if the request is passing secure iparams in the body or URL, you will receive this status.
401Is returned if you performed an unauthorized request.
429Is returned when the number of requests exceeds the threshold.
500Is returned if the server encountered an unexpected error. If this error persists, contact us at support@freshdesk.com.
502Is returned when there is a network error. If this error persists, contact us at support@freshdesk.com.
503Is returned when the service is temporarily unavailable.
504Is returned when there is a timeout error while processing the request.