Guides › API Development & Testing
API Testing with Postman: Complete Practical Guide
Learn API testing with Postman, requests, environments, assertions, variables, authentication, collections, automation, and CI integration.
API Testing with Postman: Complete Practical Guide
1. Introduction to API Testing
API testing verifies that an application's endpoints behave according to their requirements.
Instead of testing only the user interface, API tests send requests directly to an application interface and inspect the responses.
What You Will Learn
- HTTP methods and response inspection
- Creating and organizing requests
- Headers, query parameters, and request bodies
- Variables and environments
- Authentication and authorization testing
- Writing JavaScript assertions
- Collections and automated runs
- Negative testing and boundary cases
- Mocking, documentation, and collaboration
- Running tests in CI/CD pipelines
- Test reporting and debugging
2. What Is Postman?
Postman is a platform for working with APIs. It supports request creation, response inspection, collections, environments, test scripts, and automated execution.
You can use it to test REST APIs and many other HTTP-based interfaces.
3. Create Your First Request
- Open Postman.
- Create a new HTTP request.
- Enter a test endpoint, such as
https://jsonplaceholder.typicode.com/posts/1. - Select
GET. - Click Send.
- Inspect the status, response body, headers, and timing.
Example response:
{
"userId": 1,
"id": 1,
"title": "Example title",
"body": "Example body"
}
Public demo services are useful for practice, but do not send confidential data to services that you do not control.
4. Understand the Request Components
An HTTP request can contain:
- Method
- URL
- Query parameters
- Path parameters
- Headers
- Cookies
- Authentication information
- Body
The server's response can contain a status code, headers, and body.
Not every request uses every component. For example, GET requests commonly use query parameters and do not normally require a request body.
5. Test HTTP Methods
GET
Retrieve data.
GET /posts/1
POST
Create a resource.
POST /posts
Content-Type: application/json
{
"title": "Postman practice",
"body": "Learning API testing",
"userId": 1
}
PUT and PATCH
Test full-resource replacement and partial updates according to the API contract.
DELETE
Test deletion behavior, including the expected response code and whether the record remains accessible.
Always verify the behavior expected by the actual API rather than assuming all servers implement identical response conventions.
6. Query Parameters and Path Parameters
Path parameter example:
GET /users/42
The identifier 42 selects a particular user.
Query parameter example:
GET /products?category=books&limit=10
Use Postman's Params tab to add query parameters without manually assembling the URL.
Test missing, repeated, malformed, and out-of-range parameters.
7. Headers and Content Types
Headers provide request and response metadata.
Common headers:
Content-TypeAcceptAuthorizationCache-ControlUser-Agent
Example:
Content-Type: application/json
Accept: application/json
Check that the API returns the correct content type and handles unsupported media types appropriately.
8. Request Bodies
Postman supports several body formats, depending on the request and API:
- JSON
- Raw text
- Form URL-encoded
- Multipart form data
- Binary files
For a JSON API, select the raw body option and use JSON format.
Test empty bodies, missing fields, invalid JSON, incorrect data types, and oversized requests where appropriate.
9. Variables in Postman
Variables make requests reusable.
Example URL:
{{baseUrl}}/users/{{userId}}
Possible variables:
baseUrluserIdaccessToken
Use variables for environment-specific values instead of hardcoding URLs and identifiers in every request.
Be careful when using shared or synchronized workspaces. Do not store production secrets in a collection or environment that other people can access.
10. Environments
An environment groups variables for a particular target.
Example environments:
- Local
- Development
- Staging
- Production
A development base URL might be:
http://localhost:3000/api
A staging URL might be:
https://staging.example.com/api
Before sending requests, confirm that the selected environment is correct. Avoid running destructive test collections against production systems.
11. Write Your First Test
Postman supports JavaScript-based test scripts.
Example:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
Check the response content type:
pm.test("Response is JSON", function () {
pm.expect(pm.response.headers.get("Content-Type"))
.to.include("application/json");
});
12. Validate the Response Body
pm.test("Response contains a post", function () {
const body = pm.response.json();
pm.expect(body).to.have.property("id");
pm.expect(body.title).to.be.a("string");
pm.expect(body.userId).to.be.a("number");
});
Assertions should check the API contract, not just whether the response is syntactically valid JSON.
Avoid tests that are so broad that they pass even when important behavior is broken.
13. Test Response Time
pm.test("Response completes within the target", function () {
pm.expect(pm.response.responseTime).to.be.below(1000);
});
This is a basic threshold check, not a load test. Response times vary with the environment, network, and server load. Use performance testing tools for reliable throughput and latency analysis.
14. Test Error Responses
A good test suite includes negative cases.
Examples:
- Missing required field
- Invalid email format
- Nonexistent resource
- Invalid identifier
- Invalid token
- Expired credentials
- Insufficient permissions
- Rate limit exceeded
- Unsupported content type
Example:
pm.test("Invalid request is rejected", function () {
pm.expect([400, 422]).to.include(pm.response.code);
});
In a real test, prefer the exact status code defined by your API contract rather than allowing multiple codes without a reason.
15. Authentication Testing
APIs may use sessions, bearer tokens, API keys, or other authentication methods.
Example bearer-token header:
Authorization: Bearer YOUR_ACCESS_TOKEN
In Postman, configure authentication through the Authorization tab where possible.
Test:
- Request without credentials.
- Request with invalid credentials.
- Request with expired credentials.
- Request with valid credentials.
- Request to a resource the user is not allowed to access.
Do not expose real tokens in screenshots, shared collections, logs, or source control.
16. Authorization and Access Control
Authentication alone is not enough.
Test that users cannot read or modify records belonging to other users unless explicitly permitted.
For example, if user A requests /api/users/42, the API must verify whether user A is authorized to access that record.
Include tests for role-based permissions and object-level authorization.
Use only systems and accounts that you are authorized to test.
17. Collections
Collections group related requests.
A collection might contain:
- Create user
- Login
- Retrieve profile
- Update profile
- List records
- Delete test record
Use folders to organize tests by feature or workflow. Add descriptions and example responses to make the collection understandable to teammates.
18. Pre-request Scripts
Pre-request scripts run before a request is sent.
They can be used to set dynamic variables, calculate values, or prepare test data.
pm.variables.set("requestId", `test-${Date.now()}`);
Use dynamic values carefully so that tests remain reproducible and can clean up the records they create.
19. Set Variables from Responses
For example, save a newly created resource ID:
const body = pm.response.json();
pm.test("Creation returned an ID", function () {
pm.expect(body.id).to.exist;
});
if (body.id !== undefined) {
pm.collectionVariables.set("createdUserId", String(body.id));
}
The following request can use:
{{baseUrl}}/users/{{createdUserId}}
Make sure that the response is valid before saving a value for later requests.
20. Chaining Requests
A workflow can create a record and then retrieve it.
- Send the create request.
- Store the returned identifier.
- Send a GET request using that identifier.
- Assert that the returned record matches the created record.
- Delete the record during cleanup if appropriate.
This tests a workflow rather than isolated endpoints.
Plan cleanup so that repeated runs do not create unlimited test data.
21. Data-Driven Testing
Data-driven tests run the same request against multiple sets of input.
Example test cases:
| Input | Expected result |
|---|---|
| Valid email | Accepted |
| Missing email | Rejected |
| Invalid email format | Rejected |
| Empty name | Rejected |
| Overlong name | Rejected |
Use collection runners or supported iteration-data features to test multiple inputs. Keep test data deterministic and avoid real personal data.
22. Mock Servers
Mock servers return predefined responses without requiring a complete backend implementation.
They can help frontend developers:
- Work before the backend is ready.
- Test loading and error states.
- Demonstrate API flows.
- Develop against a stable contract.
Mocks do not prove that the real backend works correctly. Test against the actual service before release.
23. API Documentation
Postman collections can include descriptions, example requests, and example responses.
Good documentation should explain:
- What the endpoint does
- Authentication requirements
- Request fields
- Response structure
- Status codes
- Error cases
- Rate limits
- Versioning
- Example workflows
Keep documentation consistent with the actual API behavior.
24. Run Collections Automatically
Postman supports automated collection execution. The exact runner and CLI workflow depends on the installed Postman version and tooling.
A typical automated workflow is:
- Check out the project.
- Install required tools.
- Start the test environment.
- Load safe test variables.
- Execute the collection.
- Save reports.
- Fail the pipeline when required tests fail.
- Clean up test resources.
For CLI execution, consult the current official documentation for the supported command and authentication requirements.
25. API Testing in CI/CD
Run API tests during pull requests, scheduled builds, and release workflows.
A useful test pipeline includes:
- Fast smoke tests
- Contract checks
- Integration tests
- Authentication and authorization checks
- Regression tests
- Optional performance tests
Store secrets in the CI platform's secret manager. Do not commit production tokens or credentials.
26. Debugging Failed Tests
When a request fails:
- Check the URL and HTTP method.
- Verify the active environment.
- Inspect query parameters and path variables.
- Check request headers and body.
- Review the response status and body.
- Inspect authentication and permissions.
- Check server logs where authorized.
- Reproduce the failure with a minimal request.
- Correct the test or implementation.
- Rerun related regression tests.
Distinguish a failing API from a faulty test expectation.
27. Common API Testing Mistakes
- Testing only successful requests.
- Checking status codes but ignoring response content.
- Hardcoding environment-specific URLs.
- Sharing access tokens.
- Ignoring authorization failures.
- Depending on unpredictable external test data.
- Forgetting cleanup after creating records.
- Treating one response-time check as a load test.
- Running destructive tests against production.
- Failing to maintain collections when the API changes.
28. Practical Projects
Beginner
- Test a public demo API
- Create a collection for CRUD operations
- Validate status codes and response fields
Intermediate
- Test login and protected routes
- Automate a user registration workflow
- Add negative test cases and environment variables
Advanced
- Build a full regression collection
- Run tests in CI/CD
- Validate role-based permissions
- Generate reports for a versioned API
29. Learning Roadmap
Week 1
Learn HTTP requests, headers, methods, status codes, and JSON.
Week 2
Build collections, environments, and assertions.
Week 3
Practice authentication, negative testing, request chaining, and cleanup.
Week 4
Automate collections and integrate API tests into a CI pipeline.
30. Final Checklist
- Create and organize requests.
- Configure environments and variables.
- Test request bodies and headers.
- Validate status codes and response schemas.
- Cover invalid input and error responses.
- Test authentication and authorization.
- Chain related requests.
- Clean up test data.
- Automate collection execution.
- Integrate tests into CI/CD.
- Protect secrets and test environments.
Conclusion
Postman is useful for exploring APIs and building repeatable tests. A strong API test suite checks correctness, validation, access control, error behavior, and important workflows—not only whether a request returns a successful status.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.