Write pre-request scripts to add dynamic behavior in Insomnia

Uses: Insomnia
TL;DR

Use pre-request scripts on a Collection in Insomnia to carry out pre-processing such as setting variable values, parameters, headers, and body data for requests.

Prerequisites

Download and install Insomnia.

For this tutorial, you’ll need a collection in Insomnia. A collection is essential for this tutorial to function, but creating one isn’t the focus of this guide. Use the following to add a pre-configured collection to Insomnia: Run in Insomnia

This pre-configured collection contains:

Add a pre-request script

In this example, we’ll configure a pre-request script that sets a variable in the request:

  1. In Insomnia, navigate to the “Flight Service 0.1.0” document.
  2. Click the Collections tab.
  3. In the sidebar of your collection, select the GET A specific flight by flight number request.
  4. Click the Scripts tab on the request.
  5. Insomnia provides example pre-request scripts. From the Pre-request tab of Scripts, click Variable Snippets at the bottom of the pane and select Set an environment variable.
  6. In the example script, replace variable_name with flightNumber and variable_value with KA0285. The script should look like the following:
    insomnia.environment.set("flightNumber", "KA0285");
    

Validate the pre-request script

Now that we created a pre-request script, we can validate it by sending a GET request to the /flights/{flightNumber} endpoint:

  1. Click Send. You should get a 200 status code and the following response:
    {
     "number": "KA0285",
     "route_id": "LHR-SFO",
     "scheduled_arrival": "2024-04-03T11:10:00Z",
     "scheduled_departure": "2024-04-03T22:15:00Z"
    }
    

FAQs

Yes, you can copy and paste your pre-request scripts directly from Postman into an Insomnia pre-request script.

No, you can only run pre-request scripts from a collection or a collection that was generated from a document.

Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!