API Testing with Postman
🌐 What is a Web Service?
A web service is a software system designed to support interoperable machine-to-machine
communication over a network, typically the internet.
It allows different applications (often written in different languages or running on different
platforms) to communicate with each other using standard protocols.
🧩 In Simple Terms:
A web service is like a waiter between your app and a remote server:
Your app says: “Hey, I need some data.”
The web service listens, understands the request, does the job, and returns the
result.
📦 Common Features:
Feature Description
Platform Independent Works across different systems/languages (e.g., Java ↔ Python)
Uses Web Protocols HTTP/HTTPS, XML, JSON
Interoperable Helps different apps talk to each other seamlessly
Stateless Does not store user state unless explicitly built to do so
🛠️ Types of Web Services:
Type Description
SOAP Uses XML format and strict protocol (older, heavy)
REST Lightweight, uses HTTP verbs (GET, POST, etc.), supports JSON/XML (most
common)
GraphQL A newer alternative to REST for more efficient data queries
🌐 How Web Services Work — Step by Step
Web services allow two applications to talk to each other over the internet, typically using
HTTP protocols.
📦 Basic Components of a Web Service:
1. Client – The system/app making the request (e.g., your phone app or browser).
2. Web Service (Server) – The system responding to the request with data or actions.
3. Internet (Network) – Medium through which the request and response are sent.
🔄 Workflow of a Web Service:
🧩 Step-by-Step Example:
Let us say a mobile weather app wants to know the temperature in Delhi.
1. Client Sends Request
The app (client) sends an HTTP request to the weather web service:
sql
CopyEdit
GET https://api.weather.com/current?city=Delhi
2. Web Server Receives Request
The web service (on the server) receives the request.
3. Server Processes the Request
It reads the parameters (city=Delhi),
Checks its database or external sources,
Prepares a response.
4. Server Sends Response
It sends back a structured response, often in JSON:
json
CopyEdit
"city": "Delhi",
"temperature": "34°C",
"condition": "Sunny"
5. Client Receives & Displays Data
The app reads the response and displays:
☀️ Sunny, 34°C in Delhi
📊 Protocols & Formats Used:
Aspect Common Technologies
Transport HTTP / HTTPS
Data Format JSON, XML
Methods GET, POST, PUT, DELETE (for REST)
Style REST, SOAP, GraphQL
🧩 Analogy:
Think of a web service like ordering food:
You → customer (client)
Waiter → web service
Kitchen → server (actual backend/database)
You tell the waiter what you want (make a request), he brings your food (response).
✅ Summary:
Step Action
1. Client Request App sends HTTP request (e.g., GET weather data)
2. Web Service Server receives and processes it
3. Server Response Sends back data (e.g., JSON)
4. Client Output App reads and shows info to user
🔗 Relationship Between WSDL & UDDI:
Concept Role
WSDL Describes how to use a web service
UDDI Tells where to find the service (and its WSDL)
🎯 Summary:
Term Stands For Use
WSDL Web Services Description Language Defines the structure and methods of a
SOAP web service
UDDI Universal Description, Discovery, and A directory for finding and publishing web
Integration services
Postman is a popular collaboration platform for API development. It allows developers and
testers to design, test, document, and monitor APIs efficiently. Here is a complete overview
to get you started:
🔧 What is Postman Used For?
1. API Testing (Manual & Automated)
2. Sending HTTP Requests (GET, POST, PUT, DELETE, etc.)
3. Debugging APIs
4. Mocking APIs
5. Automating Test Suites
6. Creating API Documentation
7. Collaboration (via Workspaces & Collections)
🚀 Why API Testing is Important?
API (Application Programming Interface) testing is essential for validating the
functionality, reliability, performance, and security of the communication between
different software components — especially in backend services, mobile apps, and
microservices.
✅ Key Reasons to Do API Testing
1. Test Core Business Logic Early
UI can change frequently, but APIs represent the core functionality.
Testing at the API layer helps catch bugs before they reach the UI.
2. Faster & More Efficient
API tests are faster than UI tests.
Easier to maintain and automate in CI/CD pipelines.
3. Language Independent
APIs use protocols like HTTP and formats like JSON/XML, so they can be tested with
any tool/language.
4. Better Coverage
You can test all possible input combinations, edge cases, and error messages.
APIs expose more functions than just those accessible through the UI.
5. Early Detection of Bugs
Catch issues like:
o Invalid data
o Business rule violations
o Security vulnerabilities (e.g., unauthorized access)
6. Improves Test Automation
API testing is easy to integrate with test automation tools (e.g., Postman, Newman,
REST-assured, JUnit).
Crucial for Shift Left Testing (early testing in the SDLC).
7. No Need for UI
APIs can be tested even when the frontend is not ready.
Useful for backend-first or mobile-first development.
🔑 Main Categories of APIs
Type Description Example
1. Open API (Public Available to external users, Google Maps API, Twitter API
API) open to everyone
2. Internal API Used within an organization Company’s HR or finance system
(Private API) only API
3. Partner API Shared with specific partners, Uber using Google Maps API
access controlled
4. Composite API Combines multiple APIs into Microservices that fetch order +
one call customer data in one API
🔧 Types by Protocol/Standard
Type Description Format
1. REST API Most widely used; stateless, easy to use JSON / XML
Representational State Transfer
2. SOAP API Older, used in enterprise; strict structure XML
Simple Object Access Protocol
3. GraphQL API Flexible queries; get only the data you need JSON
4. gRPC API High performance; used in microservices Protocol Buffers
5. WebSocket API Real-time, two-way communication JSON / Binary
📌 Comparison of REST vs SOAP vs GraphQL
Feature REST SOAP GraphQL
Format JSON, XML XML only JSON
Speed Fast Slower Very Fast
Flexibility Medium Rigid High
Real-time No No With extensions
Support
Used In Web/Mobile Banking, enterprise Modern APIs (e.g., GitHub,
APIs apps Shopify)
🎯 When to Use What?
REST API → Default choice for web/mobile apps (simple, flexible)
SOAP API → When strict contracts and security are needed (e.g., payments)
GraphQL API → When frontend needs specific data shapes (modern apps)
WebSocket → For chat apps, live dashboards (real-time use cases)
gRPC → For internal microservices where speed matters
🔵 What is a REST API?
REST stands for Representational State Transfer.
A REST API is a type of API that follows the principles of REST architecture and uses standard
HTTP methods like:
GET (read),
POST (create),
PUT/PATCH (update),
DELETE (delete).
📜 The 6 Constraints of REST (by Roy Fielding)
To be called a RESTful API, it must follow all six constraints:
1. Client–Server Architecture
📌 Definition:
The client (frontend) and server (backend) must be separate systems that can evolve
independently.
💡 Example:
Your React app (client) calls a Flask API (server) — they interact via API, but are developed
separately.
2. Statelessness
📌 Definition:
Each API call must contain all the information needed — the server should not store session
state.
💡 Example:
Each request includes the auth token and user ID, so the server does not “remember”
anything.
3. Cache ability
📌 Definition:
Responses must define whether they can be cached, and for how long.
💡 Example:
A GET request for user profile can be cached for 10 minutes to reduce server load.
4. Uniform Interface
📌 Definition:
A consistent way to access resources using URIs, HTTP methods, and standard formats (like
JSON).
💡 Example:
GET /users/101 → Fetch user
DELETE /users/101 → Delete user
Same structure for all resources.
Key parts of uniform interface:
Resource Manipulation via representations
Self-descriptive messages
5. Layered System
📌 Definition:
The system can have multiple layers (e.g., API gateway, load balancer, security layer)
between client and server.
💡 Example:
Your client calls an API gateway, which routes to microservices securely.
6. Code on Demand (Optional)
📌 Definition:
Servers can optionally send executable code (e.g., JavaScript) to the client to run.
💡 Example:
A web API sends a JS function to validate form input on the client side.
🧩 TL; DR Summary:
# Constraint Purpose
1 Client–Server Separation of concerns
2 Stateless No session on server
3 Cacheable Performance boost
4 Uniform Interface Standard access pattern
5 Layered System Scalability & flexibility
6 Code on Demand Optional client-side logic
🎯 API Test Strategy:
Type Focus
✅ Functional Testing Core features (CRUD, status codes)
⚠️ Negative Testing Missing/invalid data
🛡️ Security Testing Auth, tokens, rate limits
⚡ Performance Testing Speed under load
🔄 Regression Testing Re-check after code changes
🔁 Automation Use scripts or CI tools (Newman, Jenkins)
🆚 SOAP vs REST
Feature SOAP (Simple Object Access REST (Representational State
Protocol) Transfer)
🔤 Full Form Simple Object Access Protocol Representational State Transfer
⚙️ Type Protocol Architectural Style
📦 Format Only XML JSON, XML, HTML, Text (mostly
JSON)
🌐 Transport Only HTTP, SMTP, TCP, etc. HTTP only (usually)
🛠️ Ease of Use Complex Simple and lightweight
⚡ Speed Slower (heavy XML) Faster (lightweight JSON)
🔐 Security High security via WS-Security Basic HTTPS or OAuth
✅ Standards Strict (WSDL, XSD) Loose (no strict rules)
🔄 Operations Works like functions (e.g., get Resource-based (e.g., GET /users/1)
User)
🧩 Testing Tools like SoapUI, Postman Tools like Postman, REST-assured
📁 Contract Requires WSDL (Web Services No contract needed (use
Description Language) Swagger/OpenAPI optionally)
🤝 Stateful Supports both stateful and Stateless only
Support stateless
📊 Use Case Enterprise apps, banking, Modern web/mobile apps,
telecom microservices
🌐 What Are HTTP Status Codes?
They are 3-digit responses returned by a server when an API request is made.
They tell you whether the request was successful, failed, or had issues.
📊 HTTP Status Code Categories
Code Range Category Meaning
1xx Informational Request received, processing continues
2xx Success Request was successful
3xx Redirection More steps needed (like a redirect)
4xx Client Error Problem with the request
5xx Server Error Problem on the server
✅ 2xx – Success
Code Meaning Example
200 OK Standard success GET /user/1 returns user data
201 Created New resource created POST /users to create a new
user
202 Accepted Request accepted but not yet Async upload job
processed
204 No Success, no response body DELETE /user/5 was successful
Content
❌ 4xx – Client Errors
Code Meaning Example
400 Bad Request Invalid input or malformed Missing required field
JSON
401 Unauthorized Missing/invalid auth token Not logged in
403 Forbidden Authenticated but not Role-based denial
allowed
404 Not Found Resource does not exist Wrong URL or user ID
405 Method Not Wrong HTTP method Sending POST instead of GET
Allowed
409 Conflict Duplicate data or conflict Registering with same email
again
422 Unprocessable Valid format but invalid data Empty password field
Entity
🛠️ 5xx – Server Errors
Code Meaning Example
500 Internal Server Error Generic failure Server crashed or code bug
502 Bad Gateway Invalid response from upstream Server A → Server B fails
503 Service Unavailable Server is down or overloaded Maintenance mode
504 Gateway Timeout Timeout from upstream service Slow microservice or DB
🔁 3xx – Redirection (Less common in APIs)
Code Meaning Use Case
301 Moved Permanently Redirect to a new URL API version changed
302 Found Temporary redirect Maintenance redirect
304 Not Modified Use cached version Optimizing bandwidth
🧩 As a QA/API Tester, you should always:
Test For How
✅ 200 OK On successful GET, POST, PUT
❌ 400, 401, 403, 404 With invalid or unauthorized inputs
💥 500, 503 By forcing backend failures or invalid formats
🧩 Header checks Validate content-type, caching, etc.
⏱️ Response Time Under acceptable threshold (e.g., < 500ms)
🧩 Tip to Remember:
Code Start Think...
2xx ✅ It worked!
4xx ❌ You messed up!
5xx 💥 Server messed up!
🧩 Common HTTP Methods in REST API
Method Meaning Action
GET Fetch data Read a resource
POST Send new data Create a resource
PUT Update full data Replace a resource
PATCH Update part of data Modify part of a resource
DELETE Remove data Delete a resource
OPTIONS Check allowed methods What can I do here? (used in CORS)
HEAD Like GET, but no body Get metadata (headers only)
🔧 Detailed Examples (with a /users API)
Method Request Use Case
GET GET /users/101 Get user with ID 101
POST POST /users with JSON body Create a new user
PUT PUT /users/101 with full JSON Replace user 101's data
PATCH PATCH /users/101 with partial JSON Update only email or name
DELETE DELETE /users/101 Delete user 101
OPTIONS OPTIONS /users Check which methods are allowed
HEAD HEAD /users/101 Get headers for user 101 (no body)
🔁 PUT vs PATCH – What is the Difference?
Aspect PUT PATCH
Update Type Full Partial
Use Case Replace all fields Modify some fields
Idempotent? ✅ Yes ✅ Yes (ideally)
🧩 As a QA or SDET, test for:
Test Case Method
Is the data fetched correctly? GET
Can I create valid data? POST
Does it handle duplicates? POST (409 Conflict)
Can I update all fields? PUT
Can I update one field? PATCH
Can I delete safely? DELETE
Are disallowed methods blocked? OPTIONS, 405 Method Not Allowed
🧩 Tip to Remember: CRUD = POST, GET, PUT/PATCH, DELETE
CRUD Operation HTTP Method
Create POST
Read GET
Update PUT / PATCH
Delete DELETE
🧩 What are JSON and XML?
Format Full Form Used In
JSON JavaScript Object Notation REST APIs, config files, frontend-backend
XML extensible Markup Language SOAP APIs, enterprise systems, data storage
🔍 JSON (JavaScript Object Notation)
✅ Lightweight, human-readable
✅ Easy to parse in almost every programming language
✅ Default for REST APIs
🔹 Example:
"userId": 101,
"name": "Kushal Gupta",
"email": "[email protected]",
"isActive": true
🛠 Pros:
Simpler syntax
Smaller size (fast to transmit)
Easier to read/write
Native support in JavaScript
⚠ Cons:
Limited metadata
No support for attributes
No comments allowed
🔸 XML (eXtensible Markup Language)
✅ Structured, supports metadata and attributes
✅ Used in SOAP, legacy systems, config files
🔹 Example:
<user>
<userId>101</userId>
<name>Kushal Gupta</name>
<email>[email protected]</email>
<isActive>true</isActive>
</user>
🛠 Pros:
More descriptive (you can use attributes)
Supports namespaces
Can store complex hierarchical data
⚠ Cons:
Verbose and heavier
Slower to parse
Harder to read
🧩 JSON vs XML – Quick Comparison
Feature JSON XML
Syntax Lightweight, clean Verbose, tag-based
Format Key-value pairs Tree-like with tags
Data Size Smaller Larger
Readability Easier Harder
Parsing Fast Slower
Supported in REST ✅ Yes ✅ Yes
Supported in SOAP ❌ Rare ✅ Default
Schema Support Limited (JSON Schema) Strong (XSD)
Metadata/Attributes ❌ No ✅ Yes
Comments Allowed ❌ No ✅ Yes
🔥 Real-World QA Tip:
Task Preferred Format
Testing modern REST APIs JSON
Working with SOAP APIs XML
Parsing API responses JSON (faster, easier in Postman)
📚 EXAMPLE - API Endpoint (Base URL):
https://api.example.com/books
1. GET – 🔍 Retrieve Data
Used to fetch data (read-only)
📦 Example: Get details of book with ID 5
GET /books/5
✅ Response:
"id": 5,
"title": "The Alchemist",
"author": "Paulo Coelho",
"year": 1988
2. POST – ➕ Create a New Record
Used to add a new book
📦 Example: Add a new book
POST /books
Content-Type: application/json
📤 Request Body:
{
"title": "Atomic Habits",
"author": "James Clear",
"year": 2018
✅ Response:
"id": 11,
"message": "Book added successfully"
3. PUT – 📝 Update Entire Record
Used to fully replace an existing book record
📦 Example: Update book with ID 5
PUT /books/5
Content-Type: application/json
📤 Request Body:
"title": "The Alchemist (Updated)",
"author": "Paulo Coelho",
"year": 1989
✅ Replaces the entire record.
4. PATCH – 🛠️ Partial Update
Used to update only specific fields
📦 Example: Update only the year of book ID 5
PATCH /books/5
Content-Type: application/json
📤 Request Body:
"year": 1990
✅ Only the year field is changed.
5. DELETE – ❌ Remove Data
Used to delete a book
📦 Example: Delete book with ID 5
DELETE /books/5
✅ Response:
"message": "Book deleted successfully"
6. OPTIONS – 📋 Available Methods
Used to find out what methods are allowed for an endpoint
📦 Example:
OPTIONS /books
✅ Response (Headers):
Allow: GET, POST, PUT, PATCH, DELETE, OPTIONS
7. HEAD – 🔍 Only Metadata
Like GET but returns only headers, no body
📦 Example:
HEAD /books/5
✅ Response: Same headers as GET, but no JSON body.
✅ Summary Table
Method Use Example
GET Read book /books/5
POST Add book /books
PUT Replace book /books/5
PATCH Edit part of book /books/5
DELETE Remove book /books/5
OPTIONS See allowed methods /books
HEAD Check metadata /books/5
🔐 Authentication vs Authorization in API Requests
Term Meaning Question it answers
Authentication Are you really who you say you are? "Who are you?"
Authorization Are you allowed to do this action? "What can you do?"
✅ Why Do We Need Authorization in API Requests?
Because not every authenticated user should be able to access or modify everything.
🔸 Example:
Let’s say you're logged into an app with an API:
You are authenticated → the system knows who you are.
But should you be able to access admin-only endpoints like /deleteUser or
/getAllTransactions?
👉 No! That's where authorization comes in.
❓Why Does It Seem Like APIs Only Use Authorization?
It doesn't mean that authentication isn't there — in fact, authentication happens first. But:
In practice, we often refer to "Authorization headers" (like Bearer <token>), which
contain authentication info too.
So the term "authorization" is commonly used, but it's doing both:
o Verifying who you are (authentication),
o Then checking what you're allowed to do (authorization).
🔐 Common API Security Flow:
1. ✅ Login (Authentication)
o You enter credentials.
o Backend verifies and returns a token (JWT or OAuth token).
2. 📥 API Request
o You send a request like:
sql
CopyEdit
GET /user/profile
Authorization: Bearer <your_token>
3. 🔍 Backend Decodes Token
o Authenticates your identity.
o Authorizes whether you can access this endpoint.
🧩 Why the confusion?
Because in APIs, tokens (in headers like Authorization: Bearer) are doing both roles at once.
So many developers say "authorization" even though authentication is happening too.
🎯 Final Answer:
APIs absolutely use both authentication and authorization.
Authentication ensures the request is from a real, verified user.
Authorization ensures that user has the right permissions for that specific action.
They’re just often bundled together in the same Authorization header.
In Postman, a Collection is a group of saved API requests that are organized together for
easy access, sharing, testing, and automation. Think of it as a folder or container that helps
you manage related API endpoints, such as all endpoints for a single project or API.
🔹 Why use Collections?
✅ Organize multiple API requests by project/module
✅ Store authentication, variables, and headers globally
✅ Easily run a set of requests together using Collection Runner
✅ Share with teammates or export as a file
✅ Use in CI/CD pipelines with Newman
🔹 Key Components of a Collection
Component Description
Requests GET, POST, PUT, DELETE requests etc., saved with details
Folders Nested grouping of requests
Variables Global, Collection, or Environment level placeholders
Authorization Common auth settings that apply to all requests in the collection
Pre-request Script JS code that runs before a request
Tests JS code that runs after a request to validate response
Collection Runner Tool to run all/some requests in sequence
🔹 How to Create a Collection in Postman
1. Open Postman
2. Click on “Collections” tab in the sidebar
3. Click “+ New Collection”
4. Give it a name, add description, set up auth, etc.
5. Click “Add Request” to create or move requests into the collection
🔹 Example
Let’s say you are building a Book API with 3 endpoints:
GET /books
POST /books
DELETE /books/:id
You would:
Create a Collection called "Book API"
Add 3 requests under this collection
Set a base URL and auth (if needed) at the collection level
Use variables like {{base_url}}/books
🔹 Bonus: Using Collection Runner
Click your collection → Run
Configure iterations, environment, data file (CSV/JSON)
Run requests automatically with results shown in table form
Great for automation and regression testing
In Postman, variables help you store and reuse values across requests, environments, and
collections — making your workflow dynamic and maintainable.
🔹 Types of Variables in Postman
Scope Visibility
Global Available everywhere in Postman
Collection Only within the specific collection
Environment Specific to an environment (like dev,
staging, prod)
Local Only during the current request run
Data Used during collection runs with
data files
Global > Environment > Collection > Local —
Priority order (right to left)
🔸 1. Setting Variables Manually
1. Global / Environment Variables:
o Go to the "Environment" tab or "Globals"
o Click "Add"
o Define a key and a value, e.g., base_url = https://api.example.com
2. Collection Variables:
o Open the Collection → Variables tab
o Add variables just like in environment
3. Use in requests:
bash
CopyEdit
{{base_url}}/users
🔸 2. Setting Variables with Pre-request/Test Scripts (JavaScript)
You can use pm.variables, pm.environment, pm.globals, or pm.collectionVariables to set or
get values dynamically in scripts.
✅ Set Variable in Script
a. Environment Variable
javascript
CopyEdit
pm.environment.set("token", "abc123");
b. Global Variable
javascript
CopyEdit
pm.globals.set("userId", 101);
c. Collection Variable
javascript
CopyEdit
pm.collectionVariables.set("authToken", "xyz456");
d. Local Variable (request-only)
javascript
CopyEdit
pm.variables.set("tempValue", "some data"); // won't persist
✅ Get Variable in Script
javascript
CopyEdit
let token = pm.environment.get("token");
let userId = pm.globals.get("userId");
✅ Example Use Case: Set token from login response
javascript
CopyEdit
// In "Tests" tab after POST /login
let jsonData = pm.response.json();
pm.environment.set("token", jsonData.access_token);
Then use in headers of other requests:
css
CopyEdit
Authorization: Bearer {{token}}
🔹 Tips
Use environment variables when working with multiple environments (dev, staging).
Use collection variables when sharing requests with teammates without exposing
secrets.
Use scripts for dynamic workflows like chaining requests or storing tokens.
In Postman, the Environment, Pre-request Scripts, and Tests tabs help you control dynamic
behavior, automate workflows, and validate responses.
🔹 1. Environment in Postman
✅ What is it?
An Environment in Postman is a set of key-value pairs (variables) used to customize requests
for different setups — like development, staging, production.
✅ How to Create:
1. Click the Environment dropdown (top-right) → "Manage Environments"
2. Create a new environment, e.g., Dev
3. Add variables like:
ini
CopyEdit
base_url = https://dev.api.com
token = <leave blank>
4. Save and select the environment before sending requests.
✅ Use in requests:
http
CopyEdit
{{base_url}}/users
Header: Authorization: Bearer {{token}}
🔹 2. Pre-request Script
✅ What is it?
JavaScript that runs before the request is sent — often used to:
Set/modify variables
Generate tokens
Timestamps, UUIDs
Chain workflows
✅ Example:
javascript
CopyEdit
// Generate a dynamic timestamp
let timestamp = new Date().toISOString();
pm.environment.set("current_time", timestamp);
// Set a static token
pm.environment.set("token", "abc123xyz");
You can write this in the Pre-request Script tab of the request or collection.
🔹 3. Tests
✅ What is it?
JavaScript that runs after the response — used for:
Validating response status, headers, body
Saving data from response to variables
Debugging/logging
✅ Example:
javascript
CopyEdit
// Basic status code check
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Save user ID from response JSON
let res = pm.response.json();
pm.environment.set("user_id", res.id);
// Check response has a key
pm.test("Response has token", function () {
pm.expect(res).to.have.property("token");
});
🔹 Combined Example Workflow
1. Login Request
o Pre-request Script: Set static username/password
js
CopyEdit
pm.environment.set("username", "kushal");
pm.environment.set("password", "123456");
o Body (JSON):
json
CopyEdit
"username": "{{username}}",
"password": "{{password}}"
}
o Tests Tab: Store token
js
CopyEdit
let jsonData = pm.response.json();
pm.environment.set("token", jsonData.token);
2. Other Request
o URL: {{base_url}}/users
o Header:
css
CopyEdit
Authorization: Bearer {{token}}
✅ 1. What is an Environment in Postman?
🔸 Interview Answer:
An Environment in Postman is a set of key-value variables that help us configure different
setups like development, staging, or production. It makes our API requests dynamic and
reusable.
🔸 Example Use Case:
env
CopyEdit
base_url = https://dev.api.com
token = <to be set dynamically>
🔸 Usage in URL/Header:
http
CopyEdit
{{base_url}}/users
Header → Authorization: Bearer {{token}}
✅ 2. What is a Pre-request Script?
🔸 Interview Answer:
A Pre-request Script is JavaScript code that runs before the actual API request is sent. It is
used to set variables, generate timestamps or tokens, and chain request logic.
🔸 Common Use Cases:
Generate timestamp/UUID
Set dynamic headers or tokens
Call another API to fetch a value
🔸 Example:
javascript
CopyEdit
let timestamp = new Date().toISOString();
pm.environment.set("current_time", timestamp);
// Set static token
pm.environment.set("token", "abc123xyz");
✅ 3. What is a Test Script?
🔸 Interview Answer:
A Test Script in Postman is JavaScript code that runs after the response is received. It is used
to validate response status, structure, and content, and to store values for chaining.
🔸 Use Cases:
Check HTTP status code
Validate keys/values in response
Save data (e.g., user ID, token) from response to environment
🔸 Example:
javascript
CopyEdit
// Check status
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Extract token
let json = pm.response.json();
pm.environment.set("token", json.token);
// Validate key presence
pm.test("Response has token", function () {
pm.expect(json).to.have.property("token");
});
✅ 4. Variable Scopes (Important in Interviews)
Scope Access Level Setter Code
Global All requests pm.globals.set("key", value);
Environment Current selected environment pm.environment.set("key", value);
Collection Only within collection pm.collectionVariables.set(...);
Local Only within the current request pm.variables.set(...);
🔸 Priority Order (High to Low): Local → Data → Collection → Environment → Global
✅ 5. Real-life Scenario to Explain
We have a login API that returns a token. We extract this token in the Test Script of the login
request and store it in an environment variable. For all subsequent requests, we set the
Authorization header dynamically using the token stored.
✅ 6. Bonus: Common Interview Questions
Question What to Say
Why use environments? To avoid hardcoding values like URLs or tokens and easily
switch between dev/stage/prod.
How to debug scripts? Use console.log() and open the Postman Console.
Can you reuse tokens? Yes, by extracting them from a response and saving to
environment variables.
What’s the difference Pre-request runs before request is sent; Tests run after
between pre-request and response is received.
test scripts?
How to validate a response Use pm.expect(response).to.have.property("key") or JSON
structure? schema validation.
✅ TL;DR Cheatsheet for Interviews
Concept Purpose Key Methods/Functions
Environment Dynamic values (e.g. URL, pm.environment.set/get
tokens)
Pre-request Setup before request pm.variables.set, date, UUID
Tests Validate response & extract data pm.test, pm.expect,
pm.response.json()
Debugging Console for logs & errors console.log()
✅ 1. Request Parameters
🔸 What are they?
Request parameters are key-value pairs sent in the URL query string (after ?) to filter or
modify a request.
🔸 Example:
http
CopyEdit
GET https://api.example.com/users?age=25&gender=male
Parameter Value
age 25
gender male
🔸 Use in Postman:
Method: GET
Enter URL: https://api.example.com/users
Go to Params tab
o Key = age, Value = 25
o Key = gender, Value = male
🔸 Interview Tip:
Request parameters are mostly used in GET requests to send optional data for filtering,
sorting, or pagination.
✅ 2. Path Variables
🔸 What are they?
Path variables are dynamic parts of the URL path, often used to access a specific resource.
🔸 Example:
http
CopyEdit
GET https://api.example.com/users/101
Here, 101 is a path variable representing the user_id.
🔸 Use in Postman:
URL: https://api.example.com/users/:user_id
Go to Path Variables tab (or directly use {{user_id}} in URL)
Set:
o Key: user_id, Value: 101
🔸 Interview Tip:
Path variables are mandatory and used to identify a specific resource like user ID, product
ID, etc.
✅ 3. Request Body
🔸 What is it?
The Request Body is the actual data sent to the server in POST, PUT, or PATCH requests —
usually in JSON, form-data, or raw format.
🔸 Example (JSON body for POST request):
json
CopyEdit
"name": "Kushal",
"email": "[email protected]"
🔸 Use in Postman:
Method: POST or PUT
Go to Body tab
o Select raw
o Choose JSON
o Paste the JSON payload
🔸 Interview Tip:
Request body is used to send structured data (like JSON) when creating or updating a
resource.
✅ Summary Table for Interview
Feature Used In Sent Via Example URL/Data
Query Mostly URL ?page=2&sort=name
Params GET
Path All REST URL path /users/101
Variables
Request POST/PUT Request { "name": "Kushal", "email":
Body body "
[email protected]" }
✅ Example API Request with All Three
http
CopyEdit
PUT https://api.example.com/users/101?notify=true
Request Body:
"name": "Kushal Gupta",
"email": "[email protected]"
Element Value
Path Variable 101 (user ID)
Request Param notify=true
Request Body JSON with name & email