GUIDE / api
Postman Tutorial: UI, Collections, Environments, and Tests
Postman tutorial for beginners: learn the Postman UI, collections, environments, variables, Tests tab, pre-request scripts, Collection Runner, and Newman.
This Postman tutorial is a tool walkthrough: the request builder, collections and folders, environments and variables, the Authorization and Tests tabs, pre-request scripts, Collection Runner, and Newman in CI. Postman is one of the fastest ways to learn HTTP behavior because you can inspect real responses immediately, then turn those calls into repeatable checks.
If you need an end-to-end workflow for one REST resource (CRUD, auth matrices, negative cases, and data-driven runs), use how to test a REST API with Postman. For broader API testing theory, pair this with the API testing tutorial.
What Postman Is and Why Testers Use It
Postman is an API platform commonly used to:
- Send HTTP requests
- Organize endpoints into collections
- Manage environment variables
- Write JavaScript assertions
- Share API examples with teammates
- Run suites via Collection Runner or Newman
It is popular because the feedback loop is immediate. You craft a request, click Send, and see status codes, headers, and JSON bodies without first scaffolding a code project.
When Postman Is a Great Fit
- Learning a new API
- Manual exploratory API testing
- Building a living catalog of endpoints
- Lightweight automation for regression packs
- Collaborating with developers on request examples
When You May Outgrow Pure Postman
- Very complex setup logic better expressed in code
- Monorepo native test frameworks already in place
- Advanced parallel data factories and custom infra
- Strict type safety requirements across large suites
Many teams stay hybrid: Postman for exploration and contract discovery, code for deep automation. That is a healthy outcome, not a failure.
Postman Building Blocks
| Building block | Purpose |
|---|---|
| Request | One HTTP call |
| Collection | Group of requests and folders |
| Folder | Subgroup by resource or flow |
| Environment | Variable set for local/staging/prod |
| Globals | Cross environment variables, use sparingly |
| Pre-request script | JS that runs before the request |
| Tests script | JS assertions after the response |
| Collection Runner | Runs many requests in order |
| Newman | CLI runner for CI and terminals |
| Monitor | Scheduled cloud runs in Postman platform |
Understanding these pieces prevents the common mess of random unsaved requests.
Step 1: Send Your First Request
- Open Postman and create a workspace.
- Click New -> HTTP Request.
- Set method to
GET. - Enter a public sample URL or your local API, for example
https://httpbin.org/get. - Click Send.
Inspect:
- Status code
- Response time
- Body
- Headers
This is the core loop of API work: arrange request, act by sending, assert on response.
First Useful Checks Without Scripts
Even before writing tests, ask:
- Did I get the status I expect?
- Is the content type correct?
- Are required fields present?
- Does an error message make sense for bad input?
Step 2: Create a Collection
Collections keep work reusable.
Example structure:
Shop API
Auth
Login
Refresh token
Products
Create product
Get product
List products
Update product
Delete product
Orders
Create order
Get order
Naming tips:
- Use clear resource names
- Include method intent in the request name
- Keep happy path and negative requests distinct
- Put setup requests in an Auth or Setup folder
Save every request you care about. Unsaved tabs are where knowledge goes to die.
Step 3: Use Environments
Environments store variables such as:
baseUrl = https://staging.example.com
buyerToken = <secret>
adminToken = <secret>
productId =
orderId =
Reference them in requests:
{{baseUrl}}/api/products/{{productId}}
Authorization header example:
Bearer {{buyerToken}}
Environment Discipline
| Do | Do not |
|---|---|
| Separate local and staging | Point casual tests at production with write access |
| Keep secrets out of shared dumps when possible | Commit plain tokens into public repos |
| Document required variables | Use one overloaded global for everything |
| Reset disposable ids during runs | Rely on yesterday's leftover ids forever |
Create at least:
localstaging
Production should be carefully limited if used at all for automated writes.
Step 4: Add Authentication
Common patterns in Postman:
Bearer Token
Authorization type: Bearer Token, value {{buyerToken}}.
API Key
Header such as X-API-Key: {{apiKey}}.
Basic Auth
Username and password fields, useful for simple protected sandboxes.
Login Request That Sets a Token
In the Tests tab of a login request:
pm.test("login returns 200", function () {
pm.response.to.have.status(200);
});
const body = pm.response.json();
pm.environment.set("buyerToken", body.accessToken);
Later requests can use {{buyerToken}} without manual copy paste. This is the beginning of real suite design.
Step 5: Write Tests in Postman
Open the Tests tab. Postman runs this JavaScript after the response arrives.
Basic Assertions
pm.test("status is 200", function () {
pm.response.to.have.status(200);
});
pm.test("response is json", function () {
pm.response.to.be.json;
});
pm.test("body has id", function () {
const body = pm.response.json();
pm.expect(body).to.have.property("id");
});
Asserting Business Fields
pm.test("product name matches request", function () {
const body = pm.response.json();
pm.expect(body.name).to.eql("Trail Runner");
pm.expect(body.price).to.eql(12000);
});
Response Time Guardrail
pm.test("responds in under 1s", function () {
pm.expect(pm.response.responseTime).to.be.below(1000);
});
Use time checks as soft smoke signals, not precise performance engineering. Dedicated load tools are better for true capacity work.
Negative Case Example
pm.test("missing name returns 422", function () {
pm.response.to.have.status(422);
});
pm.test("error mentions name", function () {
const body = pm.response.json();
pm.expect(JSON.stringify(body).toLowerCase()).to.include("name");
});
For status code meaning and nuances such as 401 vs 403, keep REST API status codes nearby.
Step 6: Pre-request Scripts Examples
Pre-request scripts run before the request. They are ideal for timestamps, signatures, dynamic emails, and computed headers.
Unique Email for Signup
const email = `buyer.${Date.now()}@example.test`;
pm.environment.set("newBuyerEmail", email);
Request body:
{
"email": "{{newBuyerEmail}}",
"password": "ValidPass#2026"
}
Timestamp Header
pm.request.headers.add({
key: "X-Request-Time",
value: new Date().toISOString(),
});
Simple HMAC Style Signature Sketch
const crypto = require("crypto-js");
const body = pm.request.body ? pm.request.body.raw : "";
const secret = pm.environment.get("signingSecret");
const signature = crypto.HmacSHA256(body, secret).toString();
pm.request.headers.add({ key: "X-Signature", value: signature });
Keep secrets in the environment, not in the script text committed to public places.
Skip Logic Guard
if (!pm.environment.get("buyerToken")) {
throw new Error("buyerToken is missing. Run Auth/Login first.");
}
Failing fast with a clear message beats mysterious 401 piles later in the run.
Step 7: Chain Requests Into Flows
A practical order create flow:
- Login -> save
buyerToken - Create product as admin -> save
productId - Create order as buyer with
productId-> saveorderId - Get order -> assert totals and status
- Delete or cancel order if cleanup is needed
Save IDs From Create Responses
pm.test("created product", function () {
pm.response.to.have.status(201);
const body = pm.response.json();
pm.environment.set("productId", body.id);
});
Use Saved IDs
GET {{baseUrl}}/api/products/{{productId}}
Chaining turns isolated calls into scenario coverage. That is where Postman becomes more than a fancy curl GUI.
Step 8: Postman Collection Runner With Environments
Collection Runner executes a folder or whole collection.
How to use it:
- Open the collection.
- Click Run.
- Choose the environment.
- Select which requests to include.
- Set iterations if using data files.
- Run and review pass/fail per request and per test.
Data Driven Runs
Provide a CSV or JSON file for iterations:
name,price
Alpha,1000
Beta,2000
Gamma,3000
Reference values as {{name}} and {{price}} in the body. Each iteration substitutes a row.
Runner Tips
- Put auth setup first
- Keep destructive requests intentional
- Use folders to run only Products or only Orders
- Read assertion failures before rerunning everything blindly
Collection Runner is ideal for local regression loops and demos. Newman is better for CI.
Step 9: Automate Postman Tests With Newman CI
Newman runs collections from the command line.
Install
npm install -g newman
Or as a dev dependency:
npm install -D newman
Basic Run
npx newman run collections/shop-api.json -e env/staging.json
Useful Flags
npx newman run collections/shop-api.json \
-e env/staging.json \
--reporters cli,junit \
--reporter-junit-export reports/newman.xml \
--delay-request 100
Sample GitHub Actions Step
- name: Run Postman collection
run: |
npx newman run collections/shop-api.json \
-e env/ci.json \
--env-var "buyerToken=${{ secrets.BUYER_TOKEN }}" \
--reporters cli,junit \
--reporter-junit-export reports/newman.xml
Inject secrets at runtime. Do not store staging passwords in the committed environment file if your repository is broadly shared.
Postman vs Newman
| Dimension | Postman app | Newman |
|---|---|---|
| Interface | GUI | CLI |
| Best use | Build and explore | Automate and CI |
| Assertions | Same collection tests | Same collection tests |
| Collaboration | Workspaces and sharing | Files and pipeline artifacts |
| Scheduling | Monitors / cloud features | Cron and CI schedules |
If someone says "we automated Postman," they often mean Newman or Postman Monitors running the same collections you built by hand.
Designing a Clean Postman Suite
Folder by Resource, Tag by Purpose
Inside Products:
- Create product (happy)
- Create product missing name
- Create product unauthorized
- Get product
- Get missing product
This mirrors the case design discipline from how to write API test cases.
Collection Level Scripts
You can add scripts at folder or collection scope for shared assertions, such as response time ceilings or expected header presence. Shared scripts reduce duplication, but keep them obvious so failures remain understandable.
Variable Scope Cheatsheet
| Scope | Lifetime | Example |
|---|---|---|
| Local | One request script | Temporary computed value |
| Environment | Selected environment | baseUrl, tokens |
| Collection | Across that collection | Resource path prefixes |
| Global | Everywhere | Rare shared constants |
Prefer environment scope for most suite data.
Example: Complete Create and Read Product
Request: Create Product
POST {{baseUrl}}/api/products
Body:
{
"name": "Trail Runner",
"price": 12000,
"sku": "{{sku}}"
}
Pre-request:
pm.environment.set("sku", `sku-${Date.now()}`);
Tests:
pm.test("status 201", () => pm.response.to.have.status(201));
pm.test("returns product fields", function () {
const body = pm.response.json();
pm.expect(body.name).to.eql("Trail Runner");
pm.expect(body.sku).to.eql(pm.environment.get("sku"));
pm.environment.set("productId", body.id);
});
Request: Get Product
GET {{baseUrl}}/api/products/{{productId}}
Tests:
pm.test("status 200", () => pm.response.to.have.status(200));
pm.test("persisted fields match", function () {
const body = pm.response.json();
pm.expect(body.id).to.eql(pm.environment.get("productId"));
pm.expect(body.name).to.eql("Trail Runner");
});
This pair already beats a single orphan create call with no follow up.
Collaboration and Versioning Tips
- Export collections regularly or use official source control workflows your team standardizes on
- Review collection changes like code
- Document required environment keys in a README
- Avoid personal naming like
final-final-v3-Pramod - Delete dead requests that no longer match the API
Treat collections as test assets, not personal scratchpads.
Common Mistakes in Postman API Testing
Mistake 1: No Assertions
A saved request without tests is documentation, not a test. Both are useful, but do not confuse them.
Mistake 2: One Giant Unstructured Collection
Hundreds of randomly named requests make onboarding painful. Folders and naming conventions are mandatory after week one.
Mistake 3: Hardcoded Base URLs Everywhere
Use {{baseUrl}}. Hardcoded hosts make environment switches error prone.
Mistake 4: Reusing the Same Email or SKU Forever
Unique data prevents false failures in shared environments and parallel runs.
Mistake 5: Checking Only 200 on Auth Heavy Endpoints
Add explicit 401 and 403 cases. Authorization bugs are high severity. See API authentication testing for deeper matrices.
Mistake 6: Secrets in Shared Exports
Scrub tokens before publishing collections to broad audiences.
Mistake 7: Never Running the Whole Flow
Individually green requests can still fail as a sequence if variables are not set. Use Collection Runner often.
Troubleshooting Guide
| Symptom | Likely cause | What to try |
|---|---|---|
| All requests 401 | Missing or expired token | Re-run login, check header format |
| 404 on create follow up | Wrong id variable or base path | Print productId, verify route |
| Tests pass locally, fail in CI | Environment differences | Compare env files and secrets |
| Intermittent failures | Shared data or eventual consistency | Unique data, short retry only if contract allows |
| JSON parse errors | HTML error page returned | Log status and body text first |
When debugging, reduce to one request, prove it, then rebuild the chain.
Practical Learning Plan for One Week
Day 1
Send GET and POST requests. Inspect bodies and codes.
Day 2
Build a collection with environment variables.
Day 3
Add Tests assertions for happy and negative cases.
Day 4
Add login pre-flow and token chaining.
Day 5
Run Collection Runner with multiple iterations.
Day 6
Run the same collection with Newman locally.
Day 7
Wire Newman into CI and publish a report artifact.
By the end of the week you will have a mini API regression system, not only a tool demo.
How Postman Fits a Larger Quality Strategy
Postman skills make you faster at:
- Reproducing UI bugs at the service layer
- Validating backend deploys before full UI regression
- Communicating exact failing payloads to developers
- Building smoke packs for staging
They do not replace thinking about risk, states, and coverage design. Keep using structured case design and status code literacy. Expand into contract testing when consumer producer boundaries multiply.
Practice on Real Flows
- Pick three endpoints in an app you know.
- Create a collection with happy path and two negatives each.
- Chain create -> read -> update -> delete.
- Run it in Collection Runner.
- Execute it with Newman.
- Intentionally break an assertion and confirm CI would fail.
Then continue building judgment with practical challenges after you sign up for QABattle. Tool fluency plus risk based thinking is the combination that makes API testers valuable.
Writing Better Assertions Without Overfitting
Overfitting happens when tests assert every field, including volatile ones.
Usually assert:
- Status code
- Critical business fields
- Error codes for negative paths
- Tokens or ids you will chain
Often avoid asserting:
- Exact full timestamps unless format matters
- Entire unsorted debug blobs
- Randomly generated server fields you do not control
- Marketing copy in error messages if codes exist
Example balanced test:
pm.test("order created", function () {
pm.response.to.have.status(201);
const body = pm.response.json();
pm.expect(body.status).to.eql("pending");
pm.expect(body.total).to.be.a("number");
pm.expect(body.id).to.be.a("string").and.not.empty;
pm.environment.set("orderId", body.id);
});
Working With Query Params and Path Variables
Postman supports path variables such as :productId.
URL:
{{baseUrl}}/api/products/:productId
Path variable value:
{{productId}}
Query params belong in the Params table so encoding stays correct:
| Key | Value |
|---|---|
| limit | 20 |
| status | active |
This is cleaner than hand building query strings for every case.
Mock Servers and Early Parallel Work
Postman can mock responses before a backend is ready. That helps frontend and QA agree on contract shapes early. Treat mocks as temporary agreements. Always revalidate against real services before release.
A useful pattern:
- Agree example responses with developers.
- Build client and some tests against examples.
- Switch environment to real staging.
- Fix drifts immediately.
Governance for Shared Workspaces
As more people edit collections, establish rules:
- Who can modify shared staging environments
- How secrets are stored
- How request naming works
- When to archive deprecated endpoints
- How breaking assertion changes are reviewed
Without governance, collections rot into a museum of stale 2022 payloads.
Comparing Postman Scripts to Coded Tests
| Need | Postman | Coded suite |
|---|---|---|
| Fast exploration | Excellent | Slower setup |
| Non developer collaboration | Strong | Mixed |
| Complex loops and helpers | Possible but awkward | Natural |
| Type safety | Limited | Strong in TS/Java |
| Custom reporting | Via reporters | Fully flexible |
| Same language as app | Not always | Often yes |
There is no single right answer. Many strong teams keep Postman for discovery and smoke narrative checks, then code deeper packs.
Headers, Cookies, and Content Types
Many API defects live in transport details, not JSON fields.
Checks worth adding:
pm.test("content-type is json", function () {
pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});
For cookie auth APIs, confirm cookies are set on login and sent on later requests. Postman cookie management can hide bugs if you assume browser like behavior while the real mobile client does something different. Mirror the client you are protecting.
For file uploads, set the correct multipart form data body and assert both status and resulting stored metadata through a follow up GET.
End to End Mini Lab
Build this lab in one sitting:
- Collection
Users API - Environment
local - Request login with token capture
- Request create user with unique email
- Request get user
- Request delete user
- Negative request create with missing email
- Collection Runner all requests
- Newman run producing JUnit output
When that lab is green, you understand the Postman path from curiosity to CI.
Keeping Collections Honest Over Time
APIs drift. Collections rot unless someone owns them.
Monthly hygiene:
- Delete requests for retired endpoints
- Update examples when required fields change
- Re-export or sync the collection used in CI
- Rotate any leaked or aging tokens
- Re-run the full Collection Runner after major backend releases
- Compare failing assertions with current API docs and fix the weaker side
A Postman suite is only as trustworthy as its last honest maintenance pass. Treat it like production test code, because that is what it becomes once Newman runs in CI.
Final Takeaway
A good Postman tutorial should get you past clicking Send and into suite thinking. Organize requests into collections, externalize config through environments, write assertions in Tests, generate dynamic data in pre-request scripts, execute flows with Collection Runner, and automate the same assets with Newman in CI.
Start small with one resource and a clean happy path plus negatives. Then grow into auth chains, data driven iterations, and pipeline execution. Postman becomes powerful when your collection tells a clear story about how the API is supposed to behave, and when every important story has assertions that can fail loudly when the contract breaks.
FAQ
Questions testers ask
How do beginners use Postman for API testing?
Create a request with method and URL, add auth and headers, send sample payloads, inspect status code and body, then save requests into a collection with environments for base URLs and tokens. Add Tests scripts for assertions and run the collection with Collection Runner or Newman.
How do you write tests in Postman?
Open the Tests tab on a request and write JavaScript using pm.test and pm.expect. Assert status codes, headers, JSON fields, and response times. You can also set collection variables from responses so later requests reuse ids and tokens automatically.
What is the difference between Postman and Newman?
Postman is the application for building and exploring API requests, collections, and scripts. Newman is the command line collection runner used to execute those collections in CI pipelines and terminals without the desktop UI.
What is the Postman Collection Runner?
Collection Runner executes an entire collection or folder of requests in sequence, applying an environment, optional data files, and iteration counts. It is the bridge between manual request clicking and repeatable suite execution.
Should teams use Postman or coded API tests?
Many teams use both. Postman is excellent for exploration, collaboration, and fast assertions. Coded suites may fit complex logic, custom reporting, or monorepo workflows better. Choose based on maintainability needs, not fashion.
How do you run Postman tests in CI?
Export or sync the collection and environment, install Newman in the pipeline, run newman with the collection path and environment file, then publish the CLI output or reporters as build artifacts. Fail the job when assertions fail.
RELATED GUIDES
Continue the route
How to Test a REST API with Postman
How to test a REST API with Postman end to end: CRUD flows, auth, assertions, negative cases, side effects, and data-driven runs for QA teams.
API Testing Tutorial: A Beginner's Complete Guide
API testing tutorial for beginners: learn REST API checks, CRUD test cases, tools, status codes, and a practical checklist for reliable API quality.
REST API Status Codes: The Complete Reference for Testers
Master REST API status codes with a complete tester cheat sheet for 2xx, 4xx, and 5xx responses, error validation, and practical test design.
How to Write API Test Cases
How to write API test cases with practical templates, CRUD examples, auth checks, negative paths, and a review checklist for reliable service coverage.
Postman Collection Runner Tutorial
Postman Collection Runner tutorial: run collections, environments, data files, iterations, assertions, Newman CI, and practical tips for stable API suites.
API Authentication Testing: OAuth, JWT, and API Keys
Learn API authentication testing for OAuth 2.0, JWT expiry and refresh flows, API keys vs bearer tokens, and broken authentication test cases.