Variables & Scripts in Postman
Variables in Postman
What are Variables?
Variables are placeholders for values used in requests, scripts, or
collections.
Why to use Variables?
• To avoid hardcoding values.
• To make scripts reusable and dynamic.
• To manage configurations for different environments.
Where Can Variables Be Used?
• In URLs, headers, request bodies, or scripts.
Types of variables in Postman:
1. Global Variable (Accessible everywhere):
url_global = [Link]
2. Environment Variable (Specific to an environment like QA or
Prod):
url_qa_env = [Link]
3. Collection Variable (Specific to a collection of requests):
url_collect = [Link]
4. Local Variable (Specific to a single request):
url_local = [Link]
5. Data Variable (Values provided through CSV/JSON files in the
collection runner).
[Link] [Link]
Accessing Variables in URLs:
Use {{variable_name}} to reference variables in the request URL.
Example:
{{url_global}}/api/users?page=2
{{url_qa_env}}/api/users?page=2
{{url_collect}}/api/users?page=2
{{url_local}}/api/users?page=2
Postman Scripts
Postman scripts can be written at different stages:
1. Pre-request scripts: Run before the request is sent.
2. Post-response scripts: Run after receiving the response.
Workflow: Pre-request Script → Request → Response → Post-response
[Link] [Link]
• Collection: A group of requests.
• Folder: Subgroups within a collection.
• Request: Individual HTTP requests (GET, POST, etc.).
Creating and Managing Variables with Scripts
Creating Variables in Pre-request Scripts
You can set variables before sending a request using JavaScript.
• Global Variable:
[Link]("userid_global", "2");
• Environment Variable:
[Link]("userid_qa_env", "2");
• Collection Variable:
[Link]("userid_collect", "2");
• Local Variable:
[Link]("userid_local", "2");
[Link] [Link]
Retrieving and Removing Variables in Post-response Scripts
• Retrieve a Variable Value:
[Link]([Link]("userid_global"));
[Link]([Link]("userid_qa_env"));
[Link]([Link]("userid_collect"));
[Link]([Link]("userid_local"));
• Unset (Remove) a Variable:
[Link]("userid_global");
[Link]("userid_qa_env");
[Link]("userid_collect");
[Link]("userid_local");
Using Variables Inside the Request Body
You can set and use variables in the request body to make dynamic
requests.
1. Create Local Variables in Pre-request Script:
[Link]("name", "Pavan");
[Link]("job", "Trainer");
2. POST Request Example:
[Link] [Link]
URL: [Link]
Request Body:
{
"name": "{{name}}",
"job": "{{job}}"
}
Here, {{name}} and {{job}} will be replaced with the values "Pavan" and
"Trainer" dynamically.
[Link] [Link]