Implement 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
-
You have defined a script in Script Editor.
-
You have defined an API in API Designer.
Procedure
To implement a pre-request hook, follow these steps:
-
In the API Designer, go to the Operations tab.
-
Attach a pre-request hook script to an operation.
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
-
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.
-
Create a new script.
-
Search for the API and the specific operation.
-
Drag and drop the API in the script.
Right-click on the script and select Code Snippets.
-
Go 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.