API
TEST

API Testing with Postman Guide

REST API · HTTP METHODS · STATUS CODES · COLLECTIONS · ENVIRONMENTS · TESTS · AUTHENTICATION · AUTOMATION

🎓 Next Gen QA IT Coaching Classes
📞 Mr. Khan Sir  |  8700350994
API Testing Postman & REST Assured Online & Offline B.Tech / BCA / MCA CBSE / ICSE / Polytechnic
API Basics · REST · HTTP Methods · Request Structure · Response Structure
What is an API?
API
Application Programming Interface — a set of rules that allows one application to communicate with another. Acts as a messenger between client and server.
REST API
Representational State Transfer. Most popular API architecture. Uses HTTP protocol. Stateless — each request is independent.
API Testing
Directly testing the business logic at the API layer — without UI. Faster, more reliable, finds bugs early.
Endpoint
The URL where the API can be accessed. e.g. https://api.example.com/users
Base URL
Root URL of the API. e.g. https://api.example.com — all endpoints are added after this.
Client
The one who SENDS the request. e.g. Postman, browser, mobile app.
Server
The one who RECEIVES request and SENDS back a response with data.
HTTP Methods
GET Read Data
Retrieve data from server. No request body. Safe & idempotent. e.g. Get all users, Get user by ID.
POST Create Data
Send data to create a new resource. Has request body (JSON). Not idempotent — creates new record each time.
PUT Update (Full)
Update entire resource. Replaces ALL fields. If field missing — it gets deleted. Idempotent.
PATCH Update (Partial)
Update ONLY specific fields. Other fields stay unchanged. More efficient than PUT.
DELETE Delete Data
Delete a resource from server. Usually no request body. Returns 200 or 204 on success.
HEAD Headers Only
Same as GET but returns ONLY headers, no body. Check if resource exists without downloading.
OPTIONS Allowed Methods
Returns allowed HTTP methods for an endpoint. Used in CORS preflight requests.
HTTP Request Structure
// Complete HTTP Request Structure // 1. REQUEST LINE GET /api/users/1 HTTP/1.1 // 2. HEADERS Host: api.example.com Content-Type: application/json Authorization: Bearer eyJ...token Accept: application/json // 3. REQUEST BODY (POST/PUT/PATCH only) { "name": "John Doe", "email": "john@example.com", "age": 25 } // 4. QUERY PARAMETERS (GET requests) // URL: /api/users?page=1&limit=10 page=1 limit=10 sort=name
HTTP Response Structure
// Complete HTTP Response Structure // 1. STATUS LINE HTTP/1.1 200 OK // 2. RESPONSE HEADERS Content-Type: application/json Content-Length: 245 X-Request-ID: abc-123 // 3. RESPONSE BODY (JSON) { "id": 1, "name": "John Doe", "email": "john@test.com", "status": "active", "createdAt": "2025-01-01" }
HTTP Status Codes
2xx — Success
200OKGET/PUT success, data returned
201CreatedPOST success, new resource created
202AcceptedRequest accepted, processing later
204No ContentSuccess, no body returned (DELETE)
3xx — Redirection
301MovedResource permanently moved
304Not ModifiedCached version is valid
4xx — Client Errors
400Bad RequestInvalid request data/syntax
401UnauthorizedAuthentication required/failed
403ForbiddenAuthenticated but no permission
404Not FoundResource doesn't exist
405Method Not AllowedHTTP method not supported
409ConflictDuplicate data, state conflict
422UnprocessableValidation failed
429Too Many RequestsRate limit exceeded
5xx — Server Errors
500Internal ErrorServer crashed/bug
502Bad GatewayInvalid response from upstream
503Service UnavailableServer down/overloaded
504Gateway TimeoutUpstream server timeout
Postman Interface · Collections · Environments · Variables · Request Types
Postman Interface Overview
Collections
Folder to organize related API requests. e.g. "Login API", "User API". Share & run as a suite.
Workspace
Project area where collections, environments, and APIs are stored. Personal or Team workspace.
Request Tab
Where you build your API request — method, URL, headers, body, params, auth.
Response Panel
Shows server response — status code, time, size, body, headers, cookies.
Environment
Set of variables for different setups — Dev, QA, Staging, Prod. Switch with one click.
Runner
Run entire collection automatically — all requests in sequence with test reports.
Console
View request/response logs and debug scripts. Press Ctrl+Alt+C to open.
Postman Keyboard Shortcuts
Ctrl + NNew request
Ctrl + SSave request
Ctrl + EnterSend request
Ctrl + Alt + COpen Console
Ctrl + /Search
Collections — Step by Step
Create Collection
Left panel → Click + icon → New Collection → Name it → Add Description → Create
Add Request
Right-click Collection → Add Request → Name it → Choose Method → Enter URL → Save
Add Folders
Right-click Collection → Add Folder → Group requests by module (Login, Users, Orders)
Run Collection
Click ▶ Run button → Collection Runner opens → Select collection → Click Run
Export Collection
3 dots ⋯ next to collection → Export → Save as JSON → Share with team
Import Collection
File → Import → Select JSON file or paste URL → Collection appears in sidebar
Collection Structure
// Recommended collection structure 📁 User Management API 📁 Auth POST Login POST Logout POST Refresh Token 📁 Users GET Get All Users GET Get User By ID POST Create User PUT Update User DEL Delete User 📁 Negative Tests GET Invalid User ID POST Missing Fields
Environments & Variables
Create Environment
Environments tab → + New → Name it (e.g. "QA Environment") → Add variables
Environment Variables
Key-value pairs. e.g. base_url = https://qa-api.example.com. Use {{base_url}} in requests.
Variable Types
Global (all collections), Environment (current env), Collection (one collection), Local (one request)
Setting Variables in Scripts
// Set environment variable pm.environment.set("token", value); pm.environment.set("userId", "123"); // Get environment variable const token = pm.environment.get("token"); const url = pm.environment.get("base_url"); // Set global variable pm.globals.set("apiKey", "abc123"); const key = pm.globals.get("apiKey"); // Set collection variable pm.collectionVariables.set("key", "val"); // Delete variable pm.environment.unset("token"); // Use in URL — double curly braces // URL: {{base_url}}/api/users/{{userId}}
Request — Params, Headers, Body
Query Params Tab
// Add in Params tab OR directly in URL // URL: /api/users?page=1&limit=10 Key | Value page | 1 limit | 10 sort | name filter | active
Headers Tab
// Common headers to add Content-Type | application/json Authorization | Bearer {{token}} Accept | application/json X-API-Key | {{apiKey}}
Body Tab — Raw JSON (POST/PUT/PATCH)
// Select: Body → raw → JSON { "name": "John Doe", "email": "john@example.com", "phone": "9876543210", "role": "student", "active": true }
Body — form-data (file upload)
// Select: Body → form-data Key | Value | Type username | john | Text profile_pic | file | File ← click to upload
Postman Tests Scripts · pm.test() · pm.expect() · Pre-request Scripts · Assertions
Writing Tests — pm.test()
// Basic test structure pm.test("Test description", function() { pm.expect(value).to.equal(expected); }); // ── STATUS CODE TESTS ── pm.test("Status is 200", function() { pm.expect(pm.response.code).to.equal(200); }); pm.test("Status is 201", () => { pm.response.to.have.status(201); }); // Check status in range pm.test("Success response", () => { pm.expect(pm.response.code) .to.be.oneOf([200, 201, 204]); }); // ── RESPONSE TIME TEST ── pm.test("Response under 2000ms", () => { pm.expect(pm.response.responseTime) .to.be.below(2000); }); // ── RESPONSE BODY TEXT ── pm.test("Body has 'success'", () => { pm.expect(pm.response.text()) .to.include("success"); });
JSON Response Tests
// Parse JSON body first const json = pm.response.json(); // ── VALUE ASSERTIONS ── pm.test("Name is John", () => { pm.expect(json.name).to.equal("John"); }); pm.test("ID is a number", () => { pm.expect(json.id).to.be.a("number"); }); pm.test("Email is string", () => { pm.expect(json.email).to.be.a("string"); }); pm.test("Active is true", () => { pm.expect(json.active).to.be.true; }); // ── NULL & UNDEFINED ── pm.expect(json.name).to.not.be.null; pm.expect(json.id).to.not.be.undefined; // ── ARRAY TESTS ── pm.test("Returns array", () => { pm.expect(json.users).to.be.an("array"); pm.expect(json.users.length).to.be.above(0); pm.expect(json.users).to.have.lengthOf(10); }); // ── CONTAINS CHECK ── pm.expect(json.message) .to.include("created"); pm.expect(json.roles) .to.include("admin");
Property & Key Assertions
const json = pm.response.json(); // ── CHECK KEY EXISTS ── pm.test("Has id field", () => { pm.expect(json).to.have.property("id"); }); pm.test("Has email field", () => { pm.expect(json).to.have.property("email"); }); // ── NESTED PROPERTIES ── pm.expect(json.address) .to.have.property("city"); pm.expect(json.address.city) .to.equal("Delhi"); // ── MULTIPLE KEYS ── pm.expect(json).to.include.keys( ["id", "name", "email"]); // ── HEADER ASSERTIONS ── pm.test("Content-Type is JSON", () => { pm.expect(pm.response.headers .get("Content-Type")) .to.include("application/json"); }); // ── SCHEMA VALIDATION ── const schema = { "type": "object", "required": ["id", "name"] }; pm.test("Schema valid", () => { pm.expect(tv4.validate(json, schema)) .to.be.true; });
Pre-request Scripts
// Pre-request runs BEFORE the request // Used to: set variables, generate data // ── SET DYNAMIC DATA ── const timestamp = new Date().getTime(); pm.environment.set("timestamp", timestamp); // ── GENERATE RANDOM EMAIL ── const random = Math.floor(Math.random()*999); pm.environment.set("email", `user${random}@test.com`); // ── CHAIN REQUESTS ── // Save response for next request const json = pm.response.json(); pm.environment.set("userId", json.id); pm.environment.set("token", json.token); // ── CONSOLE LOG (debug) ── console.log("Token:", token); console.log("Response:", json); // ── RUN NEXT REQUEST ── // In Tests tab — skip to specific request postman.setNextRequest("Get User by ID"); // Stop execution postman.setNextRequest(null);
Authentication · Bearer Token · API Key · Basic Auth · CRUD API Examples · JSON
Authentication Types
No Auth
Public APIs — no authentication needed. e.g. weather API, news API.
API Key
Pass a key in header or query param. e.g. X-API-Key: abc123 OR ?apikey=abc123
Bearer Token
Most common. Header: Authorization: Bearer eyJhbGci... JWT token after login.
Basic Auth
Base64 encoded username:password. Authorization: Basic dXNlcjpwYXNz
OAuth 2.0
Token-based auth. Get token first → use token in subsequent requests. Used by Google, GitHub.
Digest Auth
More secure than Basic Auth. Password hashed with MD5. Not commonly used now.
Auth Tab in Postman
// Auth Tab → Select Type // Bearer Token Type: Bearer Token Token: {{token}} // Basic Auth Type: Basic Auth Username: admin Password: admin123 // API Key Type: API Key Key: X-API-Key Value: {{apiKey}} Add to: Header
Complete CRUD — User API
// BASE URL: https://api.example.com // ── CREATE USER (POST) ── POST /api/users Body (JSON): { "name": "Rahul Verma", "email": "rahul@qa.com", "phone": "9876543210" } Expected: 201 Created // ── GET ALL USERS (GET) ── GET /api/users Expected: 200 OK + array // ── GET USER BY ID (GET) ── GET /api/users/{{userId}} Expected: 200 OK + single user // ── UPDATE USER (PUT) ── PUT /api/users/{{userId}} Body: { "name": "Rahul K Verma" } Expected: 200 OK // ── PARTIAL UPDATE (PATCH) ── PATCH /api/users/{{userId}} Body: { "phone": "9999999999" } Expected: 200 OK // ── DELETE USER (DELETE) ── DEL /api/users/{{userId}} Expected: 200 or 204
JSON Format — Complete Guide
// JSON Data Types { "string": "Hello World", "number": 42, "decimal": 3.14, "boolean": true, "nullValue": null, "array": ["a", "b", "c"], "nested": { "city": "Delhi", "pin": "110001" } } // Real user response JSON { "id": 101, "name": "Khan Sir", "email": "khan@nextgenqa.com", "role": "trainer", "active": true, "courses": ["Selenium", "Playwright"], "address": { "city": "Delhi", "country": "India" }, "createdAt": "2025-01-01T10:00:00Z" } // Array of users [ { "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" } ]
Login & Token Chaining
// STEP 1: Login request POST /api/auth/login Body: { "email": "admin@test.com", "password": "Admin@123" } // STEP 2: Save token in Tests tab const json = pm.response.json(); pm.environment.set("token", json.token); pm.environment.set("userId", json.user.id); // STEP 3: Use token in next request // Auth Tab → Bearer Token → {{token}} // OR Headers: Authorization: Bearer {{token}} // STEP 4: Use userId in URL GET /api/users/{{userId}}
Path vs Query Parameters
// PATH parameter — part of URL GET /api/users/123 // 123 is the path param (user ID) // QUERY parameter — after ? GET /api/users?page=1&limit=20 // Both combined GET /api/users/123/orders?status=paid
Newman CLI · Collection Runner · API Testing Checklist · Interview Q&A
Newman — Run Postman from CLI
What is Newman?
Command-line tool to run Postman collections without opening Postman. Used in CI/CD pipelines (Jenkins, GitHub Actions).
// Install Newman npm install -g newman // Run a collection newman run collection.json // Run with environment newman run collection.json \ -e environment.json // Run with HTML report npm install -g newman-reporter-html newman run collection.json \ -r html --reporter-html-export report.html // Run specific folder newman run collection.json \ --folder "Login Tests" // Set iterations (run N times) newman run collection.json -n 3 // Run with data file (CSV) newman run collection.json \ -d testdata.csv // Run with delay (ms) newman run collection.json --delay-request 500
API Testing Checklist
✅ Status Code
Verify correct HTTP status code (200, 201, 400, 404, 500 etc.) for each scenario.
✅ Response Body
Verify all expected fields exist with correct values and data types.
✅ Response Headers
Verify Content-Type, Auth headers, CORS headers are correct.
✅ Response Time
API should respond within acceptable limit (e.g. under 2000ms).
✅ Negative Testing
Test with invalid data, missing fields, wrong data types, unauthorized access.
✅ Authentication
Test with valid token, expired token, no token, wrong token.
✅ Error Messages
Verify proper error messages for 400/401/403/404/500 errors.
✅ Data Validation
Test boundary values, required fields, field length limits, special characters.
✅ CRUD Operations
Verify Create → Read → Update → Delete flow works end to end.
✅ Idempotency
GET, PUT, DELETE called multiple times should give same result.
Interview Q&A — Part 1
Q: What is API Testing?
Testing APIs directly at the business logic layer without UI. Validates functionality, reliability, performance, and security of APIs.
Q: GET vs POST?
GET retrieves data (no body, idempotent). POST creates new data (has body, not idempotent). GET params in URL, POST params in body.
Q: PUT vs PATCH?
PUT replaces entire resource (all fields required). PATCH updates only specific fields (partial update). PATCH is more efficient.
Q: What is 401 vs 403?
401 = Not authenticated (no login/token). 403 = Authenticated but no permission (logged in but not authorized to access).
Q: What is idempotent?
Calling the same API multiple times gives the same result. GET, PUT, DELETE are idempotent. POST is NOT idempotent.
Q: What is REST API?
Representational State Transfer — architectural style using HTTP, stateless, resource-based URLs, JSON/XML responses.
Q: What to verify in API response?
Status code, response body fields and values, data types, response time, headers, error messages.
Interview Q&A — Part 2
Q: What is Postman Environment?
Set of key-value variables for different setups (Dev/QA/Prod). Switch environments with one click. Access with {{variable}}.
Q: What is Collection Runner?
Postman feature to run entire collection automatically. Executes all requests in sequence and shows pass/fail report.
Q: What is Newman?
CLI tool to run Postman collections from command line. Used in CI/CD pipelines. npm install -g newman.
Q: How to chain API requests?
In Tests tab of first request, extract value using pm.response.json() and save it using pm.environment.set(). Use {{variable}} in next request URL.
Q: Path param vs Query param?
Path param is part of URL: /users/123. Query param is after ?: /users?page=1. Path for specific resource, Query for filtering/sorting.
Q: What is negative API testing?
Testing with invalid inputs — wrong data types, missing required fields, expired token, unauthorized access — to verify proper error handling.
Q: What is JSON Schema validation?
Validating API response structure matches expected schema — correct field names, data types, required fields. Done using tv4 or ajv in Postman.