API Testing with Postman: Build, Script, and Automate API Tests
Postman works for every stage of API testing. During development, you use it to manually explore endpoints and verify responses. As the API stabilizes, you add test scripts that automatically validate responses after each request. Once you have a collection of tested requests, you run the entire collection with Newman in your CI/CD pipeline to catch regressions on every code change. The transition from manual exploration to full automation happens incrementally without switching tools.
Set Up Your First Request
Download Postman from postman.com or use the web version. Create a free account (required for syncing collections, optional for local-only work). Click "New" and select "HTTP Request" to open the request builder.
The request builder has four key areas. The method selector (GET, POST, PUT, PATCH, DELETE, and others) determines the HTTP method. The URL field accepts the complete endpoint URL including path parameters. The tabs below the URL let you configure query parameters (Params tab), authorization (Auth tab), request headers (Headers tab), and the request body (Body tab).
For a GET request, select GET, enter the URL (for example, https://jsonplaceholder.typicode.com/posts/1), and click Send. Postman displays the response status code (200 OK), response time, response size, the response body with syntax highlighting, and the response headers. The body viewer supports JSON, XML, HTML, and raw text formats with pretty-printing and a tree view for navigating nested JSON structures.
For a POST request, select POST, enter the URL (for example, https://jsonplaceholder.typicode.com/posts), switch to the Body tab, select "raw" and "JSON" from the format dropdown, and enter a JSON body like {"title": "Test Post", "body": "This is a test", "userId": 1}. Click Send and verify the response status is 201 Created with the created resource in the response body.
The Auth tab simplifies authentication configuration. Select the auth type (Bearer Token, API Key, Basic Auth, OAuth 2.0, and others) and Postman automatically adds the correct headers. For Bearer Token auth, paste your token and Postman adds the Authorization: Bearer header to every request. For OAuth 2.0, Postman walks you through the authorization flow, obtains the token, and manages token refresh automatically.
Write Test Scripts
Postman's test scripts run after each request completes, enabling automated validation of responses. Click the "Scripts" tab (labeled "Tests" in older Postman versions), select "Post-response," and write JavaScript code that checks the response against expected values.
The pm object provides access to the response and assertion methods. To check the status code: pm.test("Status code is 200", function() { pm.response.to.have.status(200); }). To validate a JSON field: pm.test("User name is correct", function() { var json = pm.response.json(); pm.expect(json.name).to.eql("John Doe"); }). To check response time: pm.test("Response under 500ms", function() { pm.expect(pm.response.responseTime).to.be.below(500); }). To verify a header: pm.test("Content-Type is JSON", function() { pm.response.to.have.header("Content-Type", "application/json; charset=utf-8"); }).
Multiple assertions within a single pm.test() block report as one pass or fail. Use separate pm.test() blocks for each distinct validation so failures are specific and identifiable. A test that checks status code, response body, and response time in three separate blocks tells you exactly what failed. A single block with all three assertions only tells you the first failure.
JSON Schema validation catches structural issues that individual field checks miss. Postman includes the tv4 library for schema validation. Define your expected response schema as a JavaScript object, then validate: pm.test("Schema is valid", function() { var schema = { type: "object", required: ["id", "name", "email"], properties: { id: { type: "number" }, name: { type: "string" }, email: { type: "string" } } }; pm.response.to.have.jsonSchema(schema); }). This catches missing fields, wrong data types, and unexpected nulls in a single assertion.
Pre-request scripts run before the request is sent, useful for generating dynamic data. Click "Pre-request Script" (or "Pre-request" under the Scripts tab) and write JavaScript that runs before the request fires. Common uses include generating timestamps (pm.environment.set("timestamp", Date.now())), creating unique identifiers (pm.environment.set("uniqueEmail", "test+" + Date.now() + "@example.com")), and computing authentication signatures that require request-specific data.
Organize with Collections and Environments
Collections are Postman's way of grouping related requests. Create a collection for each API or microservice, then organize requests into folders by resource or workflow. A typical collection structure groups all user endpoints (/users GET, POST, PUT, DELETE) in one folder, all order endpoints in another, and multi-step workflows (like "create user, log in, place order, verify order") in a workflows folder.
Collection-level settings apply to all requests in the collection. Set authentication at the collection level and every request inherits it automatically. Set pre-request scripts at the collection level for common setup logic like token refresh. Set variables at the collection level for values shared across requests.
Environments store variable sets for different deployment targets. Create a "Development" environment with baseUrl set to http://localhost:3000, a "Staging" environment with baseUrl set to https://staging-api.example.com, and a "Production" environment with baseUrl set to https://api.example.com. In your requests, use the variable syntax to reference these values in the URL field. Switch environments from the dropdown in the top right corner of Postman, and all requests automatically target the selected environment's base URL.
Environment variables also store credentials and dynamic values. Set an authToken variable after a login request succeeds, then reference it in the Authorization header of subsequent requests. This keeps sensitive values out of the request definitions and makes it easy to test with different user accounts by switching environments.
Global variables are accessible across all collections and environments. Use them for constants that never change between environments, like API version numbers or test data that is identical everywhere. Collection variables sit between global and environment scope, available to all requests in the collection but not visible to other collections.
Chain Requests with Variables
Real API testing requires multi-step workflows where data from one response feeds into the next request. Postman handles this through variables set in test scripts and consumed in subsequent requests.
A common pattern is the authentication chain. The first request in the collection sends login credentials (POST /auth/login with username and password). The test script extracts the token from the response: var json = pm.response.json(); pm.environment.set("authToken", json.token). All subsequent requests reference this variable in their Authorization header as Bearer plus the variable reference. When the collection runs, the login executes first, stores the token, and every following request automatically includes it.
Resource creation and validation chains work similarly. A POST request creates a resource, and the test script extracts the created resource's ID: pm.environment.set("createdUserId", pm.response.json().id). The next GET request uses that ID in its URL path to fetch the created resource. The test script on the GET request verifies the data matches what was submitted. A final DELETE request uses the same ID to clean up, and its test script verifies the 204 response.
Collection Runner executes all requests in a collection sequentially, running each request's pre-request script, sending the request, and executing the test script before moving to the next request. Open the collection, click "Run," configure the number of iterations and the delay between requests, select the environment, and click "Run Collection." The results view shows pass/fail status for every test in every request, total execution time, and a summary of failures.
Data-driven testing runs the same collection multiple times with different input data. Create a CSV or JSON file with rows of test data (different usernames, emails, expected statuses). In the Collection Runner, select the data file and set the iteration count to match the number of rows. Each iteration uses the next row of data, accessible in requests and scripts through the data variable. This tests the same endpoints with dozens of input variations without duplicating requests.
Automate with Newman CLI
Newman is Postman's command-line collection runner, designed for CI/CD pipeline integration. Install it globally with npm: npm install -g newman. Export your collection from Postman as a JSON file (right-click the collection, select Export). Export your environment the same way.
Run a collection with: newman run my-collection.json -e staging-environment.json. Newman executes every request in order, runs all test scripts, and reports results in the terminal with pass/fail status for each test. The exit code is 0 for all tests passing and 1 for any failures, which CI/CD systems use to gate deployments.
Newman supports multiple output reporters. The built-in CLI reporter displays results in the terminal. Add JUnit XML output for CI integration: newman run my-collection.json -r cli,junit --reporter-junit-export results.xml. Add HTML reports for human review: install newman-reporter-htmlextra (npm install -g newman-reporter-htmlextra) and run: newman run my-collection.json -r htmlextra --reporter-htmlextra-export report.html. The HTML report includes request/response details, test results, and failure screenshots.
CI/CD integration varies by platform but follows the same pattern. In GitHub Actions, create a workflow step that installs Newman and runs your collection. In Jenkins, add a build step with the Newman command and a post-build step that parses the JUnit XML report. In GitLab CI, add a test stage that runs Newman and archives the test artifacts. Store collection and environment files in your repository so they version alongside your code and are available to the CI runner without Postman cloud access.
For teams that prefer not to export files, Newman can also run collections directly from the Postman API using a collection UID and an API key. This means the CI pipeline always runs the latest version of the collection without manual export steps. The tradeoff is a dependency on Postman's cloud service availability during CI runs.
Newman supports iteration data files, custom delays, timeout configuration, SSL certificate options, and proxy settings through command-line flags. For complex configurations, create a newman configuration file in JSON format and reference it with newman run --config newman-config.json to keep CI pipeline definitions clean.
Advanced Postman Testing Techniques
Postman Monitors run collections on a schedule (every 5 minutes, hourly, daily) from Postman's cloud infrastructure and alert you when tests fail. This provides synthetic monitoring for production APIs, catching outages, performance degradation, and behavior changes between deployments. Monitors can run from different geographic regions to test API availability and latency from various locations. Monitor results appear in Postman's dashboard with historical trends, failure details, and response time graphs.
Mock servers in Postman simulate API responses based on examples you define in your requests. When the real API is not yet built or is temporarily unavailable, the mock server returns predefined responses that let frontend developers and testers continue their work. Mock servers use the request method, URL, and headers to match incoming requests to defined examples and return the appropriate response body and status code.
Postman Flows provides a visual workflow builder for complex API test scenarios. Instead of relying on collection ordering and variable chaining, Flows lets you draw connections between requests, add conditional logic (if status code is 200, proceed to this request; if 400, go to error handling), and create loops for retry logic. This visual approach makes complex workflows easier to understand and maintain than deeply chained collection scripts.
API documentation generation from Postman collections creates browsable documentation that stays synchronized with your tests. Each request's method, URL, parameters, headers, body, and example responses are rendered as documentation pages. Adding descriptions to requests and parameters enriches the generated docs. Published documentation updates automatically when the collection changes, eliminating the documentation drift that plagues manually maintained API docs.
Postman's strength is the seamless progression from manual API exploration to fully automated testing. Start by building requests and examining responses visually. Add test scripts to automate validation. Organize into collections with environment variables for portability. Run with Newman in CI/CD for regression testing. The entire workflow uses one tool, making it the lowest-friction path to comprehensive API testing for most teams.