0
0
Postmantesting~15 mins

Why pre-request scripts prepare data in Postman - Why It Works This Way

Choose your learning style9 modes available
Overview - Why pre-request scripts prepare data
What is it?
Pre-request scripts in Postman are small pieces of code that run before an API request is sent. They prepare or modify data needed for the request, such as setting variables or generating tokens. This helps make requests dynamic and adaptable to different situations. Essentially, they set the stage so the request can run smoothly and correctly.
Why it matters
Without pre-request scripts, every API request would need to have fixed data, making tests rigid and repetitive. This would slow down testing and increase errors because testers would have to manually update data each time. Pre-request scripts automate this preparation, saving time and reducing mistakes, which leads to faster and more reliable testing.
Where it fits
Before learning about pre-request scripts, you should understand basic API requests and how to use Postman to send them. After mastering pre-request scripts, you can explore test scripts that run after requests, environment variables, and automation with Postman Collections and monitors.
Mental Model
Core Idea
Pre-request scripts act like a personal assistant who gets everything ready before you start your main task, ensuring the request has all the right data and settings.
Think of it like...
Imagine baking a cake: pre-request scripts are like measuring and mixing ingredients before putting the cake in the oven. Without this preparation, the cake won’t turn out right.
┌─────────────────────────────┐
│       Pre-request Script     │
│  (Prepare data & variables) │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│        API Request           │
│  (Uses prepared data)        │
└──────────────┬──────────────┘
               │
               ▼
┌─────────────────────────────┐
│        Test Script           │
│  (Checks response results)   │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationWhat are pre-request scripts
🤔
Concept: Introduce the basic idea of pre-request scripts as code that runs before an API request.
In Postman, a pre-request script is a small JavaScript code block that executes before sending the API request. It can set or change variables, generate tokens, or prepare any data needed for the request.
Result
You understand that pre-request scripts run first and can change how the request behaves.
Knowing that pre-request scripts run before requests helps you see how they control what data the request uses.
2
FoundationHow to write simple pre-request scripts
🤔
Concept: Learn the syntax and basic commands to write pre-request scripts in Postman.
Pre-request scripts use JavaScript. For example, you can set a variable with pm.variables.set('key', 'value'); or generate a timestamp with new Date().toISOString();. These scripts run automatically before the request.
Result
You can write a script that sets a variable or prepares data before the request runs.
Understanding the simple commands lets you customize requests dynamically.
3
IntermediateUsing variables to prepare dynamic data
🤔Before reading on: do you think variables set in pre-request scripts can change the request URL or headers? Commit to your answer.
Concept: Learn how pre-request scripts set variables that the request uses to be flexible and dynamic.
Variables set in pre-request scripts can be used in the request URL, headers, or body by using {{variableName}} syntax. For example, setting an auth token in a script lets the request use it automatically.
Result
Requests can change their data each time they run without manual edits.
Knowing variables link scripts and requests shows how automation reduces manual work and errors.
4
IntermediateGenerating authentication tokens dynamically
🤔Before reading on: do you think pre-request scripts can call external services to get tokens, or only generate tokens locally? Commit to your answer.
Concept: Use pre-request scripts to create or fetch authentication tokens needed for secure API access.
Pre-request scripts can generate tokens using JavaScript or call APIs to fetch tokens before the main request. For example, a script can create a JWT token or request a token from an auth server and save it as a variable.
Result
Your requests can authenticate automatically without manual token updates.
Understanding token generation in scripts enables secure and seamless API testing.
5
AdvancedChaining requests with prepared data
🤔Before reading on: do you think pre-request scripts can share data between multiple requests in a collection? Commit to your answer.
Concept: Learn how pre-request scripts prepare data that can be passed between requests to create workflows.
By setting environment or collection variables in pre-request scripts, you can pass data like IDs or tokens from one request to another. This chaining allows complex test scenarios where each request depends on the previous one.
Result
You can build multi-step tests that simulate real user flows.
Knowing how to share data between requests unlocks powerful end-to-end testing capabilities.
6
ExpertHandling timing and asynchronous data preparation
🤔Before reading on: do you think pre-request scripts can wait for asynchronous operations like API calls before sending the main request? Commit to your answer.
Concept: Explore how pre-request scripts manage asynchronous tasks and timing to ensure data is ready before the request runs.
Pre-request scripts can perform asynchronous calls using pm.sendRequest(), but must handle timing carefully. Postman waits for pm.sendRequest() to finish before sending the main request, allowing dynamic data fetching. Mismanaging this can cause race conditions or missing data.
Result
You can reliably prepare data from external sources before requests execute.
Understanding asynchronous behavior in pre-request scripts prevents flaky tests and ensures data consistency.
Under the Hood
Pre-request scripts run in Postman's sandboxed JavaScript environment before the HTTP request is sent. They can access and modify variables stored in different scopes (global, environment, collection, local). When asynchronous calls are made with pm.sendRequest(), Postman waits for their completion before proceeding. The prepared data is then injected into the request's URL, headers, or body using variable placeholders.
Why designed this way?
Postman designed pre-request scripts to give testers control over request data dynamically without manual changes. Running scripts before requests allows setup like authentication or data formatting. The sandboxed environment ensures security and isolation. Asynchronous support was added to handle real-world API workflows needing token fetching or data preparation.
┌───────────────────────────────┐
│ Postman Runtime Environment    │
│ ┌───────────────────────────┐ │
│ │ Pre-request Script Runs    │ │
│ │ - Sets variables           │ │
│ │ - Calls pm.sendRequest()   │ │
│ └─────────────┬─────────────┘ │
│               │               │
│               ▼               │
│ ┌───────────────────────────┐ │
│ │ Main API Request Sent      │ │
│ │ - Uses variables           │ │
│ └─────────────┬─────────────┘ │
│               │               │
│               ▼               │
│ ┌───────────────────────────┐ │
│ │ Test Script Runs After     │ │
│ └───────────────────────────┘ │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do pre-request scripts run after the API response is received? Commit to yes or no.
Common Belief:Pre-request scripts run after the API response to check or modify it.
Tap to reveal reality
Reality:Pre-request scripts run before the API request is sent, never after the response.
Why it matters:Confusing this causes testers to put response checks in pre-request scripts, which won't work and leads to failed tests.
Quick: Can pre-request scripts directly modify the API response data? Commit to yes or no.
Common Belief:Pre-request scripts can change the response data before it reaches the test scripts.
Tap to reveal reality
Reality:Pre-request scripts cannot modify response data; they only prepare data before sending the request.
Why it matters:Expecting to alter responses in pre-request scripts leads to misunderstanding test flow and broken test logic.
Quick: Do variables set in pre-request scripts persist across different requests automatically? Commit to yes or no.
Common Belief:Variables set in pre-request scripts are always saved globally and available in all requests.
Tap to reveal reality
Reality:Variables must be set in the correct scope (environment, global, collection) to persist; local variables only last for the current request.
Why it matters:Misusing variable scopes causes data to disappear unexpectedly, breaking chained requests.
Quick: Can pre-request scripts run indefinitely if they have errors? Commit to yes or no.
Common Belief:If a pre-request script has an error, Postman will keep trying to run it until it succeeds.
Tap to reveal reality
Reality:Postman stops execution on script errors and sends the request without waiting or retrying.
Why it matters:Assuming retries happen can hide bugs and cause unexpected request failures.
Expert Zone
1
Pre-request scripts run in a sandboxed environment with limited APIs, so some Node.js or browser features are unavailable, which can surprise experienced JavaScript developers.
2
The order of variable resolution matters: local variables override environment, which override global variables, affecting how prepared data is used.
3
Asynchronous pm.sendRequest() calls in pre-request scripts must be carefully managed to avoid race conditions, especially when chaining multiple requests.
When NOT to use
Pre-request scripts are not suitable for heavy data processing or long-running tasks; such logic should be handled outside Postman or in backend services. For simple static data, hardcoding or environment variables may be simpler and more efficient.
Production Patterns
In real-world API testing, pre-request scripts are used to automate authentication token refresh, generate timestamps or unique IDs, and chain requests by passing data between them. They enable continuous integration pipelines to run tests without manual intervention.
Connections
Continuous Integration (CI) Pipelines
Builds-on
Understanding pre-request scripts helps automate API tests in CI pipelines by preparing dynamic data, enabling reliable automated testing.
State Machines
Similar pattern
Pre-request scripts prepare the 'state' before a request, similar to how state machines set conditions before transitions, helping manage complex workflows.
Cooking Recipes
Builds-on
Knowing how pre-request scripts prepare data before requests is like prepping ingredients before cooking, emphasizing the importance of setup for successful outcomes.
Common Pitfalls
#1Trying to use pre-request scripts to validate API responses.
Wrong approach:pm.test('Response is OK', function() { pm.response.to.have.status(200); });
Correct approach:Place response validation code inside the Tests tab, not in pre-request scripts.
Root cause:Confusing the timing and purpose of pre-request scripts versus test scripts.
#2Setting variables without specifying scope, expecting them to persist globally.
Wrong approach:pm.variables.set('token', 'abc123');
Correct approach:Use pm.environment.set('token', 'abc123'); or pm.globals.set('token', 'abc123'); to persist variables.
Root cause:Misunderstanding variable scopes and their lifetimes in Postman.
#3Making asynchronous calls in pre-request scripts without waiting for completion.
Wrong approach:pm.sendRequest('https://api.example.com/token', function (err, res) {}); // No handling of async completion
Correct approach:Use pm.sendRequest with callback or promises and rely on Postman's built-in wait to ensure completion before sending the main request.
Root cause:Not understanding Postman's asynchronous execution model in pre-request scripts.
Key Takeaways
Pre-request scripts run before API requests to prepare or modify data dynamically.
They enable automation of tasks like setting variables, generating tokens, and chaining requests.
Understanding variable scopes and asynchronous behavior is key to effective pre-request scripting.
Misusing pre-request scripts for response validation or ignoring execution order leads to errors.
Mastering pre-request scripts unlocks powerful, flexible, and reliable API testing workflows.