Full stack dev🧑🏻‍💻

Using pre-request scripts in Postman to avoid dangerous API calls

Posted

3 min read

Cover Image for Using pre-request scripts in Postman to avoid dangerous API calls

Let's say you set up Postman requests for you and your team to easily call and test various APIs in dev/test and production. Imagine you're testing out different things in the API, doing some CRUD stuff, but then you find you out you've actually been doing it against production all along... 😱😱😱

This has actually happened to me a few years ago in my team(s). One time a fairly new team member was trying out stuff without realizing it was the production environment they were calling, and another time I was the culprit.. I was just one cup of coffee away from actually being aware of what I was doing... (don't worry, it all worked out in the end, no data was harmed during those "incidents", it only resulted in two shaken up developers 😰).

Our team relies on Postman and being able to call APIs in different environments, and I didn't want this risk to be an issue for our team members. For this reason, I decided to add a simple "lock" or fail-safe to ensure that we don't accidentally call API endpoints in production that are not of the type HTTP GET.

I decided that in cases where we'd like to use POST/PUT/DELETE etc, an override header should be required to allow the request.

For the sake of this blog post, I'll just use https://petstore.swagger.io/ to import their swagger to Postman.

1. Import the requests collection

In Postman, you'll see a button in the top left corner called Import. Click it and paste in the URL to the petstore swagger definition: https://petstore.swagger.io/v2/swagger.json.

2. Add a pre-request script

Edit the collection and add a pre-request script. This will ensure that the script will be executed for all of the requests that are under this main collection / folder.

Click the Pre-request script tab, and paste in the code (see below) and hit the save button in the top right corner.

Pre-request script:

1const allowedHttpMethods = ["GET"];
2const lockedEnvs = ["PROD"];
3
4const environmentName = pm.environment.name.toUpperCase();
5const method = pm.request.method.toUpperCase();
6const headers = pm.request.headers;
7const headerOverride = headers.find(item => item.key === 'OverrideLock');
8
9// This makes sure that we do not accidentally make potentially dangerous calls in PROD envs.
10if (!allowedHttpMethods.includes(method) && (lockedEnvs.includes(environmentName))) {
11    console.log(headerOverride);
12
13    // Ensure that the header is set, and that it is enabled (checkbox is checked)
14    if (headerOverride && headerOverride.value == 'true' && !headerOverride.disabled) {
15        console.log('Allowing the call since the override header is set.');
16        return;
17    }
18    else {
19        throw new Error("You can only perform GET requests against the production server. To override this lock set the override header 'OverrideLock' to 'true'.");
20    }
21
22}

3. Create environments in Postman

Create a new environment in Postman called PROD and add a variable called baseUrl with the value https://petstore.swagger.io/v2. Duplicate that environment and call the other one TEST.

4. Make a POST request

We will now test how the lock works for our PROD environment, and ensure that it is not blocking any calls for our TEST environment.

4.1 POST request in the TEST environment

Ensure that you have selected the TEST environment in Postman (see top right corner), and make a POST request using any of the existing requests. The request will succeed since we don't enforce the lock for the test environment.

4.2 POST request in the PROD environment

Ensure that you have selected the PROD environment in Postman, and make a POST request using any of the existing requests. The request will fail and you'll get an error explaining that you can only perform GET requests in the production environment, unless you set the override lock header.

4.1 Override the production lock

Add a new header in your request to override the lock we have put in place to protect ourselves from accidental production calls. Set the header key to OverrideLock and the value to true. Send the same request again and you'll see that you are now allowed to perform this POST request.

Success! You are now somewhat safer 🎉

Isa
Isa

More Stories

Query multiple Application Insights instances with KQL (Kusto Query Language)

Query multiple application insights instances using KQL (Kusto Query Language)...

Cover Image for C# Cosmos DB simple "lock" functionality by implementing Optimistic Concurrency Control

C# Cosmos DB simple "lock" functionality by implementing Optimistic Concurrency Control

Prevent data corruption when multiple users concurrently try to update a single Cosmos DB item in an Azure Function. Implement optimistic concurrency control using ETags and retry logic to ensure correct updates....