Introduction to Postman — Testing Your API

Postman is the industry-standard tool for developing, testing, and documenting REST APIs. In MERN development you will use it constantly — sending requests to your Express API before the React frontend exists, debugging request/response cycles, testing authentication flows, and verifying that your endpoints return the right data and status codes. In this lesson you will install Postman, learn how to send every type of HTTP request your MERN API will support, and organise your requests into a collection that serves as living documentation for your API.

Why Test the API Before Building the Frontend?

Reason Detail
Isolate problems If the API works in Postman but not in React, the bug is in the React code — not Express
Faster iteration Testing in Postman is instant — no waiting for React state updates or UI refreshes
Verify status codes Postman shows the exact HTTP status (200, 201, 400, 401, 404, 500) — React often hides these
Test error paths Easy to send malformed data, missing fields, or invalid tokens to confirm error handling works
Living documentation A saved Postman collection describes every endpoint — useful for new team members
Note: Postman is free for individuals. Download it from postman.com/downloads. Alternatively, if you prefer to stay inside VS Code, install the Thunder Client extension (covered in the previous lesson) — it provides the same core functionality without leaving the editor. Both tools are covered here; the concepts are identical.
Tip: Use Postman Environment Variables to store your base URL and auth token. Set baseUrl to http://localhost:5000 in a “Development” environment and https://yourapp.render.com in a “Production” environment. Then write all request URLs as {{baseUrl}}/api/posts. Switching between environments is one click — no manual URL editing needed.
Warning: Never commit Postman collections that contain real credentials, API keys, or production tokens. Export the collection with variables referencing environment names (e.g. {{authToken}}) rather than hardcoded values. Share the collection file in Git but manage the actual values in each developer’s local Postman environment, which is never committed.

Sending Your First Request

Step 1: Open Postman and click "New Request" (Ctrl+N / Cmd+N)

Step 2: Set the HTTP method and URL
  Method: GET
  URL:    http://localhost:5000/api/health

Step 3: Click "Send"

Step 4: Read the response
  Status:  200 OK
  Body:    { "status": "ok", "environment": "development" }
  Time:    12 ms
  Size:    48 B

Testing All HTTP Methods

── GET — Retrieve all posts ──────────────────────────────────────────────────
Method:  GET
URL:     http://localhost:5000/api/posts
Headers: (none needed for public endpoints)
Body:    (none — GET requests have no body)

── POST — Create a new post ──────────────────────────────────────────────────
Method:  POST
URL:     http://localhost:5000/api/posts
Headers: Content-Type: application/json
Body (raw JSON):
  {
    "title": "My First MERN Post",
    "body": "This is the post content.",
    "tags": ["mern", "tutorial"]
  }

── PUT — Update a post ───────────────────────────────────────────────────────
Method:  PUT
URL:     http://localhost:5000/api/posts/64a1f2b3c8e4d5f6a7b8c9d0
Headers: Content-Type: application/json
         Authorization: Bearer <your_jwt_token>
Body (raw JSON):
  {
    "title": "Updated Post Title",
    "body": "Updated content."
  }

── DELETE — Delete a post ────────────────────────────────────────────────────
Method:  DELETE
URL:     http://localhost:5000/api/posts/64a1f2b3c8e4d5f6a7b8c9d0
Headers: Authorization: Bearer <your_jwt_token>

Setting Headers and Authentication

Setting the Content-Type header:
  1. Click the "Headers" tab in your request
  2. Add key: Content-Type  value: application/json
  → Tells Express to parse the body as JSON (same as what Axios does automatically)

Setting a Bearer token for protected routes:
  Option A — Headers tab:
    Key:   Authorization
    Value: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

  Option B — Auth tab (recommended):
    Click "Auth" → Type: "Bearer Token"
    Paste your token in the Token field
    → Postman adds the Authorization header automatically

  Getting a token to test with:
    1. POST /api/auth/login with your credentials
    2. Copy the token from the response JSON
    3. Paste it into the Auth tab of protected requests

Postman Collections — Organising Your API

Create a Collection for the MERN Blog API:
  1. Click "Collections" in the left sidebar
  2. Click "+" → New Collection
  3. Name it: "MERN Blog API"

Organise with folders:
  MERN Blog API/
  ├── Auth/
  │   ├── POST Register          → POST /api/auth/register
  │   ├── POST Login             → POST /api/auth/login
  │   └── GET Current User       → GET  /api/auth/me
  ├── Posts/
  │   ├── GET All Posts          → GET    /api/posts
  │   ├── GET Single Post        → GET    /api/posts/:id
  │   ├── POST Create Post       → POST   /api/posts
  │   ├── PUT Update Post        → PUT    /api/posts/:id
  │   └── DELETE Delete Post     → DELETE /api/posts/:id
  └── Users/
      ├── GET All Users          → GET  /api/users
      └── GET User Profile       → GET  /api/users/:id

Using Environment Variables in Postman

Step 1: Create an Environment
  Click the gear icon (Environments) → Add
  Name: MERN Blog - Development
  Add variables:
    baseUrl    →  http://localhost:5000
    authToken  →  (leave blank — set after login)

Step 2: Use variables in requests
  URL: {{baseUrl}}/api/posts
  Header: Authorization: Bearer {{authToken}}

Step 3: Auto-set token after login (Tests tab)
  In the POST /api/auth/login request → Tests tab → add:
  const res = pm.response.json();
  pm.environment.set("authToken", res.data.token);
  → Now every login automatically updates {{authToken}} for all other requests

Reading the Response

Response Field What to Look For
Status code 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error
Body → Pretty Formatted JSON — check the structure and values your Express controller returned
Body → Raw Exact string sent — useful if JSON parsing fails
Headers Check Content-Type is application/json — if it is text/html Express sent an HTML error page
Time Response time in ms — flag anything over 500ms for investigation
Console View → Show Postman Console (Ctrl+Alt+C) — shows the raw request and response for debugging

Common Mistakes

Mistake 1 — Not setting Content-Type for POST requests

❌ Wrong — sending a POST with a JSON body but no Content-Type header:

POST /api/posts   Body: {"title":"Test"}
→ req.body is undefined in Express because it does not know to parse as JSON

✅ Correct — in Postman select Body → raw → JSON from the dropdown. This automatically sets the Content-Type header to application/json:

Headers tab will show: Content-Type: application/json  (auto-added by Postman)

Mistake 2 — Testing with the server not running

❌ Wrong — sending a request and getting “Error: connect ECONNREFUSED 127.0.0.1:5000”:

Could not get a response — ECONNREFUSED means nothing is listening on that port

✅ Correct — always start your Express server before testing in Postman:

cd server
npm run dev   # nodemon starts Express on port 5000
# Then test in Postman

Mistake 3 — Using an expired or incorrect JWT token

❌ Wrong — copying a token from a previous session and reusing it after it expires:

401 Unauthorized  → { "message": "Token expired" } or { "message": "Invalid token" }

✅ Correct — when you get a 401, re-run the POST /api/auth/login request to get a fresh token. Use the Postman Tests script to auto-update {{authToken}} on every successful login.

Quick Reference

Task Postman Action
New request Ctrl+N / Cmd+N
Send request Ctrl+Enter / Cmd+Enter
Set JSON body Body → raw → select JSON from dropdown
Set auth token Auth tab → Bearer Token → paste token
Create collection Collections → + → New Collection
Create environment Environments (gear icon) → Add
Use a variable {{variableName}} anywhere in URL, headers, body
Open console View → Show Postman Console (Ctrl+Alt+C)
Export collection Right-click collection → Export → Collection v2.1

🧠 Test Yourself

You send a POST request to /api/posts in Postman with a JSON body but your Express controller logs that req.body is an empty object {}. The server is running and the route is correctly defined. What is the most likely cause?