Pre-request hook script

A pre-request hook is a script that executes just before an API call is made. It allows you to modify the request options object before the request is sent via the proxy.

Prerequisites

Procedure

To implement a pre-request hook, follow these steps:

  1. Navigate to the Operations tab.

  2. Attach a pre-request hook script to an operation.

    api designer pre hook

In the pre-request hook script, you can perform the following actions:

  • Make modifications to the request, you can manipulate this object. For instance, you can add query parameters to the URL or include additional headers.

For the pre-request hook to work, the operation must go through a proxy.

The procedure for triggering the pre-request hook varies depending on the type of API.

External

Pre-request hook setup for an external API.

  1. In the General tab, enable Enable Proxy.

    This approach enables you to consistently trigger the pre-request hook whenever the API is called.

Within the pre-request script, you have the capability to perform various actions, including the ability to modify the request options.

  • View the entire request options object, use log.info(requestConfig). This will display the entire object in the logs.

Server Script

Pre-request hook setup for a server script API.

To ensure the pre-request script is activated, the API must be triggered through a script, as the request needs to pass through a proxy.

  1. Create a new script.

  2. Search for the API and the specific operation.

  3. Drag and drop the API in the script.

    Right-click on the script and choose Code Snippets.

  4. Navigate to api > your-operation and copy the code.

    It should look like this:

    const opts = {
        parameters: {},
        headers: {},
        data: {},
        body: {},
    }
    
    try {
        const response = await apis.{name-of-operation}(opts);
        console.log(response.data)
    } catch(error) {
        log.error("Error in request: ", error);
        return fail();
    }

The script is now configured and can be triggered through various methods, initiating the initial API call along with its pre-request script.

Within the pre-request script, you have the capability to perform various actions, including the ability to modify the request options.

  • View the entire request options object, use log.info(requestConfig). This will display the entire object in the logs.

Result

By using pre-request hooks, you have the flexibility to customize and optimize the API request, according to your specific requirements, and also trigger other actions through the script.