The Complete Guide to Postman: Mastering API Development and Testing

The Complete Guide to Postman: Mastering API Development and Testing

Introduction to Postman

Postman is a comprehensive API platform that simplifies every aspect of the API lifecycle. Originally launched as a Chrome extension in 2012, it has evolved into a powerful desktop application used by over 20 million developers worldwide. Postman provides tools for designing, testing, documenting, and monitoring APIs, making it an essential platform for modern software development.

Why Use Postman?

Unlike command-line tools like cURL, Postman offers:

  • Graphical Interface: Intuitive UI for API interaction
  • Collaboration Features: Team workspaces and sharing
  • Automation: Collection runners and monitors
  • Documentation: Auto-generated API documentation
  • Mock Servers: Simulate API responses before development
  • Environment Management: Context-aware API testing

Installation and Setup

Supported Platforms

Postman is available for:

  • Windows (7, 8, 10, 11)
  • macOS (10.11 or later)
  • Linux (Ubuntu 16.04+, Fedora 30+, Debian 9+)

Installation Methods

Direct Download:

  1. Visit https://www.postman.com/downloads/
  2. Select your operating system
  3. Run the installer

Package Managers:

# macOS (Homebrew)
brew install --cask postman

# Linux (Snap)
sudo snap install postman

# Windows (Chocolatey)
choco install postman

Postman Web:
Available at https://web.postman.co/ (limited functionality)

Initial Setup

  1. Launch Postman
  2. Create a free account or sign in
  3. Choose between personal or team workspace
  4. Select your preferred theme (dark/light)

Understanding the Postman Interface

Main Components

  1. Sidebar
  • History: Previous API requests
  • Collections: Grouped API requests
  • APIs: API definitions and schemas
  • Environments: Variables for different contexts
  • Mock Servers: Simulated API endpoints
  • Monitors: Scheduled API tests
  • Flows: API workflow automation
  1. Builder Tab
  • Request method dropdown (GET, POST, etc.)
  • URL input field
  • Params: Query parameters
  • Authorization: Authentication setup
  • Headers: HTTP headers
  • Body: Request payload
  • Pre-request Script: JavaScript executed before request
  • Tests: JavaScript for response validation
  • Settings: Request-specific configurations
  1. Response Panel
  • Body: Response content with pretty printers
  • Cookies: Server cookies
  • Headers: Response headers
  • Test Results: Output from test scripts
  • Status: HTTP status code and timing

Free APIs for Testing

Before we begin, here are free APIs we’ll use for examples:

  1. JSONPlaceholder – Fake REST API for testing (https://jsonplaceholder.typicode.com)
  2. ReqRes – Sample REST API (https://reqres.in)
  3. OpenWeatherMap – Weather API (free tier with signup) (https://openweathermap.org/api)
  4. Cat Facts – Random cat facts (https://catfact.ninja)
  5. JSONPlaceholder Photos – Image data (https://jsonplaceholder.typicode.com/photos)
  6. Dog CEO – Dog images API (https://dog.ceo/dog-api/)
  7. Open Library – Book information (https://openlibrary.org/developers/api)
  8. Public APIs – Directory of free APIs (https://publicapis.dev)

Making Your First API Request

Basic GET Request with JSONPlaceholder

  1. Click the + button to open a new tab
  2. Select GET from the method dropdown
  3. Enter URL: https://jsonplaceholder.typicode.com/posts/1
  4. Click Send
  5. View the response in the bottom panel

Exploring Response Formats

Postman automatically formats responses:

  • JSON: Syntax highlighting and collapsible nodes
  • XML: Tree view with expandable elements
  • HTML: Rendered view and raw HTML
  • Images: Preview of image responses
  • Plain Text: Monospaced formatting

Example JSON response:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Testing Different Free APIs

ReqRes API Example:

GET https://reqres.in/api/users/2

Cat Facts API:

GET https://catfact.ninja/fact

Dog CEO API:

GET https://dog.ceo/api/breeds/image/random

Working with Collections

Collections are groups of saved requests that can be organized, shared, and executed together.

Creating a Collection for Free API Testing

  1. Click Collections in the sidebar
  2. Click + New Collection
  3. Enter collection name: “Free APIs Testing Collection”
  4. Add description: “Collection for testing various free APIs”
  5. Click Create

Adding Multiple API Requests

Adding JSONPlaceholder requests:

  1. Right-click collection
  2. Select Add Request
  3. Name: “Get All Posts”
  4. Method: GET
  5. URL: https://jsonplaceholder.typicode.com/posts
  6. Click Save

Adding ReqRes requests:

  1. Add another request
  2. Name: “Create User”
  3. Method: POST
  4. URL: https://reqres.in/api/users
  5. Go to Body tab
  6. Select raw and JSON format
  7. Add body:
{
    "name": "morpheus",
    "job": "leader"
}
  1. Click Save

Collection Structure Example

Free APIs Testing Collection
├── JSONPlaceholder API
│   ├── GET All Posts
│   ├── GET Single Post
│   ├── POST Create Post
│   ├── PUT Update Post
│   └── DELETE Post
├── ReqRes API
│   ├── GET Users
│   ├── POST Create User
│   └── PUT Update User
├── Cat Facts API
│   ├── GET Random Fact
│   └── GET Breeds
└── Dog CEO API
    ├── GET Random Dog Image
    └── GET Breed List

API Authorization Methods with Free APIs

Most free APIs don’t require authentication, but Postman supports various methods:

1. No Auth (Default for Free APIs)

For public APIs without authentication. Most free APIs we’re using fall into this category.

2. API Key (Example with OpenWeatherMap)

After signing up for free API key at https://openweathermap.org/api:

  1. Go to Authorization tab
  2. Select API Key from Type dropdown
  3. Add to: Query Params
  4. Key: appid
  5. Value: your_api_key_here
  6. URL becomes: https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key

3. Bearer Token (Example Practice)

For APIs that use JWT tokens:

  1. Authorization tab
  2. Select Bearer Token
  3. Enter token in Token field

Testing Different Authentication Methods

Open Library API (No Auth):

GET https://openlibrary.org/search.json?q=test

Weather API (API Key Required – sign up needed):

GET https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY

Working with Variables and Environments

Creating Environments for Different APIs

Creating Development Environment:

  1. Click Environments in sidebar
  2. Click + New Environment
  3. Name: “Free APIs Environment”
  4. Add variables:
jsonplaceholder_url: https://jsonplaceholder.typicode.com
reqres_url: https://reqres.in/api
catfacts_url: https://catfact.ninja
dogceo_url: https://dog.ceo/api
openlibrary_url: https://openlibrary.org
user_id: 1
post_id: 1
  1. Click Save

Using Environment Variables in Requests

Dynamic URL Example:

GET {{jsonplaceholder_url}}/posts/{{post_id}}

Headers with Variables:

X-User-ID: {{user_id}}

Request Body with Variables:

{
    "userId": {{user_id}},
    "title": "Test Post",
    "body": "This is a test post"
}

Dynamic Variables for Testing

Postman provides dynamic variables useful for testing:

// In request body
{
    "email": "test-{{$timestamp}}@example.com",
    "username": "user{{$randomInt}}",
    "createdAt": "{{$timestamp}}",
    "referenceId": "{{$guid}}"
}

Available dynamic variables:

  • {{$guid}}: UUID v4
  • {{$timestamp}}: Current Unix timestamp
  • {{$randomInt}}: Random integer 1-1000
  • {{$randomFirstName}}: Random first name
  • {{$randomLastName}}: Random last name
  • {{$randomCity}}: Random city name

Advanced Request Configuration with Free APIs

Request Body Types with Examples

  1. none: GET requests
GET {{catfacts_url}}/fact
  1. form-data: Multipart form data
POST https://httpbin.org/post
Key: username, Value: testuser
Key: file, Value: [Select File], Type: File
  1. x-www-form-urlencoded: URL encoded form data
POST https://httpbin.org/post
Key: username, Value: testuser
Key: password, Value: test123
  1. raw: JSON, XML, etc.
POST {{reqres_url}}/users
{
    "name": "John Doe",
    "job": "Developer"
}

Testing Different Content Types

JSON Example (JSONPlaceholder):

POST {{jsonplaceholder_url}}/posts
Content-Type: application/json
{
    "title": "Test Post",
    "body": "This is a test",
    "userId": 1
}

XML Example (using httpbin):

POST https://httpbin.org/xml
Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>User</to>
  <from>Admin</from>
  <heading>Test</heading>
  <body>Test message</body>
</note>

Query Parameters with Free APIs

JSONPlaceholder with parameters:

GET {{jsonplaceholder_url}}/posts
Params:
  userId: 1
  _limit: 5

Open Library search:

GET {{openlibrary_url}}/search.json
Params:
  q: programming
  limit: 10

Headers Management Examples

Custom headers with ReqRes:

GET {{reqres_url}}/users/2
Headers:
  X-Request-ID: {{$guid}}
  X-Custom-Header: TestValue
  Accept: application/json

Writing Pre-request Scripts with Free APIs

Pre-request scripts execute JavaScript before the request is sent.

Basic Pre-request Examples

Setting Dynamic Variables:

// Generate timestamp for unique data
const timestamp = new Date().getTime();
pm.environment.set("current_timestamp", timestamp);

// Generate random user ID between 1-10
const randomUserId = Math.floor(Math.random() * 10) + 1;
pm.environment.set("random_user_id", randomUserId);

// Create unique email for testing
const uniqueEmail = `testuser_${timestamp}@example.com`;
pm.environment.set("test_email", uniqueEmail);

Dynamic Headers:

// Add timestamp header
pm.request.headers.add({
    key: 'X-Timestamp',
    value: new Date().toISOString()
});

// Add request ID header
pm.request.headers.add({
    key: 'X-Request-ID',
    value: pm.variables.replaceIn('{{$guid}}')
});

Conditional Logic:

// Skip certain requests based on environment
const skipPosts = pm.environment.get("skip_posts_test");
if (skipPosts === "true") {
    console.log("Skipping posts API test");
    pm.request.remove();
}

// Set different base URLs based on time
const currentHour = new Date().getHours();
if (currentHour >= 9 && currentHour <= 17) {
    pm.environment.set("api_env", "business-hours");
} else {
    pm.environment.set("api_env", "off-hours");
}

Complex Pre-request Example

// Generate test data for API request
function generateTestData() {
    const testData = {
        id: Math.floor(Math.random() * 1000) + 1,
        name: `Test User ${Date.now()}`,
        email: `user${Date.now()}@test.com`,
        active: Math.random() > 0.5,
        createdAt: new Date().toISOString()
    };

    // Store in environment for use in request body
    pm.environment.set("test_user_data", JSON.stringify(testData));

    // Also store individual values
    pm.environment.set("test_user_name", testData.name);
    pm.environment.set("test_user_email", testData.email);
}

// Execute on pre-request
generateTestData();
console.log("Test data generated for request");

Writing Test Scripts with Free APIs

Tests execute JavaScript after receiving the response.

Basic Test Examples for Free APIs

JSONPlaceholder Response Tests:

// Test 1: Check status code
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

// Test 2: Check response has JSON body
pm.test("Response has JSON body", function () {
    pm.response.to.be.json;
});

// Test 3: Check response structure
pm.test("Response has required fields", function () {
    const responseJson = pm.response.json();
    pm.expect(responseJson).to.have.property('userId');
    pm.expect(responseJson).to.have.property('id');
    pm.expect(responseJson).to.have.property('title');
    pm.expect(responseJson).to.have.property('body');
});

// Test 4: Check data types
pm.test("Data types are correct", function () {
    const responseJson = pm.response.json();
    pm.expect(responseJson.userId).to.be.a('number');
    pm.expect(responseJson.id).to.be.a('number');
    pm.expect(responseJson.title).to.be.a('string');
    pm.expect(responseJson.body).to.be.a('string');
});

ReqRes API Tests:

// Test for user creation
pm.test("User created successfully", function () {
    pm.response.to.have.status(201);
});

pm.test("Response contains user data", function () {
    const responseJson = pm.response.json();
    pm.expect(responseJson).to.have.property('name');
    pm.expect(responseJson).to.have.property('job');
    pm.expect(responseJson).to.have.property('id');
    pm.expect(responseJson).to.have.property('createdAt');
});

// Test response time
pm.test("Response time is acceptable", function () {
    pm.expect(pm.response.responseTime).to.be.below(1000);
});

Cat Facts API Tests:

pm.test("Cat fact received", function () {
    pm.response.to.have.status(200);
});

pm.test("Fact is a string", function () {
    const responseJson = pm.response.json();
    pm.expect(responseJson.fact).to.be.a('string');
    pm.expect(responseJson.fact.length).to.be.above(10);
});

pm.test("Length property is present", function () {
    const responseJson = pm.response.json();
    pm.expect(responseJson.length).to.be.a('number');
});

Advanced Test Patterns

Data-Driven Validation:

// Test all items in array response
const posts = pm.response.json();

pm.test("All posts have valid structure", function () {
    posts.forEach((post, index) => {
        pm.expect(post).to.have.all.keys(['userId', 'id', 'title', 'body']);
        pm.expect(post.userId).to.be.a('number');
        pm.expect(post.id).to.be.a('number');
        pm.expect(post.title).to.be.a('string');
        pm.expect(post.body).to.be.a('string');

        // Optional: Log issues
        if (!post.title || post.title.trim() === '') {
            console.warn(`Post ${post.id} has empty title`);
        }
    });
});

Environment Variable Updates from Response:

// Extract and store data from response
const responseJson = pm.response.json();

if (responseJson.id) {
    // Store the created ID for future requests
    pm.environment.set("created_post_id", responseJson.id);
    pm.test("Post ID saved to environment", function () {
        pm.expect(pm.environment.get("created_post_id")).to.equal(responseJson.id.toString());
    });
}

if (responseJson.email) {
    pm.environment.set("user_email", responseJson.email);
}

Schema Validation:

// Define expected schema
const userSchema = {
    type: "object",
    properties: {
        data: {
            type: "object",
            properties: {
                id: { type: "number" },
                email: { type: "string", format: "email" },
                first_name: { type: "string" },
                last_name: { type: "string" },
                avatar: { type: "string", format: "uri" }
            },
            required: ["id", "email", "first_name", "last_name", "avatar"]
        },
        support: {
            type: "object",
            properties: {
                url: { type: "string", format: "uri" },
                text: { type: "string" }
            },
            required: ["url", "text"]
        }
    },
    required: ["data", "support"]
};

// Test against schema
pm.test("Response matches user schema", function () {
    pm.response.to.have.jsonSchema(userSchema);
});

Performance Testing:

// Store response time for monitoring
const responseTime = pm.response.responseTime;
pm.environment.set("last_response_time", responseTime);

pm.test(`Response time ${responseTime}ms is acceptable`, function () {
    // Different thresholds for different environments
    const env = pm.environment.get("env") || "development";
    let maxTime = 1000; // default

    if (env === "production") {
        maxTime = 500;
    } else if (env === "staging") {
        maxTime = 750;
    }

    pm.expect(responseTime).to.be.below(maxTime);
});

Complete Test Suite Example

// Comprehensive test suite for JSONPlaceholder posts API
pm.test("API Tests Suite", function () {

    // 1. HTTP Status Tests
    pm.test("HTTP Status is 200 OK", function () {
        pm.response.to.have.status(200);
    });

    pm.test("Status text is OK", function () {
        pm.response.to.have.status("OK");
    });

    // 2. Headers Tests
    pm.test("Content-Type header is present", function () {
        pm.response.to.have.header("Content-Type");
    });

    pm.test("Content-Type is application/json", function () {
        pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
    });

    pm.test("Server header is present", function () {
        pm.response.to.have.header("Server");
    });

    // 3. Response Time Tests
    const responseTime = pm.response.responseTime;
    console.log(`Response time: ${responseTime}ms`);

    pm.test("Response time is under 2 seconds", function () {
        pm.expect(responseTime).to.be.below(2000);
    });

    // 4. Response Body Tests
    pm.test("Response has valid JSON", function () {
        pm.response.to.be.json;
    });

    const responseData = pm.response.json();

    pm.test("Response is an array", function () {
        pm.expect(responseData).to.be.an('array');
    });

    pm.test("Array is not empty", function () {
        pm.expect(responseData.length).to.be.above(0);
    });

    // 5. Data Structure Tests
    if (responseData.length > 0) {
        const firstItem = responseData[0];

        pm.test("First item has required properties", function () {
            pm.expect(firstItem).to.include.all.keys(['userId', 'id', 'title', 'body']);
        });

        pm.test("Property types are correct", function () {
            pm.expect(firstItem.userId).to.be.a('number');
            pm.expect(firstItem.id).to.be.a('number');
            pm.expect(firstItem.title).to.be.a('string');
            pm.expect(firstItem.body).to.be.a('string');
        });

        pm.test("ID is positive number", function () {
            pm.expect(firstItem.id).to.be.above(0);
        });

        pm.test("User ID is between 1 and 10", function () {
            pm.expect(firstItem.userId).to.be.within(1, 10);
        });
    }

    // 6. Business Logic Tests
    pm.test("All items have unique IDs", function () {
        const ids = responseData.map(item => item.id);
        const uniqueIds = [...new Set(ids)];
        pm.expect(ids.length).to.equal(uniqueIds.length);
    });

    pm.test("No empty titles", function () {
        const emptyTitles = responseData.filter(item => !item.title || item.title.trim() === '');
        pm.expect(emptyTitles.length).to.equal(0);
    });

    // 7. Store data for future tests
    if (responseData.length > 0) {
        pm.environment.set("first_post_id", responseData[0].id);
        pm.environment.set("total_posts", responseData.length);
    }

    // 8. Final summary
    console.log(`Tested ${responseData.length} posts successfully`);
});

Collection Runner with Free APIs

The Collection Runner executes multiple requests in sequence with data-driven testing capabilities.

Running a Collection of Free APIs

  1. Click Runner button (top-left)
  2. Select “Free APIs Testing Collection”
  3. Choose “Free APIs Environment”
  4. Configure:
  • Iterations: 2 (run twice)
  • Delay: 1000 ms (1 second between requests)
  1. Click Run Collection

Data-Driven Testing with CSV

Create a CSV file test_data.csv:

user_id,post_id,expected_status
1,1,200
2,50,200
999,999,404
10,101,404

Run with data file:

  1. In Collection Runner
  2. Click Select File
  3. Choose test_data.csv
  4. Data File Type: text/csv
  5. Click Run

Using Data Variables in Tests

// Access CSV data in tests
const expectedStatus = parseInt(pm.iterationData.get("expected_status"));
const userId = pm.iterationData.get("user_id");

pm.test(`Status is ${expectedStatus} for user ${userId}`, function () {
    pm.response.to.have.status(expectedStatus);
});

// Use data in request
// In request URL: {{jsonplaceholder_url}}/posts/{{post_id}}

Postman Monitors with Free APIs

Monitors schedule collection runs at regular intervals (limited on free plan).

Creating a Monitor for Free API Health Check

  1. Click Monitors in sidebar
  2. Click + New Monitor
  3. Configure:
  • Name: “Free APIs Daily Health Check”
  • Collection: “Free APIs Testing Collection”
  • Environment: “Free APIs Environment”
  • Frequency: Once a day (free plan limitation)
  • Region: North America (or closest to you)
  1. Click Create

Monitor Results Interpretation

Check monitor runs:

  1. Click on monitor name
  2. View run history
  3. Check success rate
  4. Review response times
  5. Identify failing tests

Mock Servers with Free APIs

Mock servers simulate API endpoints before backend implementation.

Creating a Mock Server for Testing

  1. Click Mock Servers in sidebar
  2. Click + New Mock Server
  3. Select “Free APIs Testing Collection”
  4. Configure:
  • Name: “Free APIs Mock Server”
  • Make private (if desired)
  1. Click Create

Configuring Mock Responses

For each request in collection:

  1. Open request
  2. Make actual request to get sample response
  3. Click Save Response button
  4. Select Save as Example
  5. Name: “Success Response”
  6. Click Save

Using Mock Server URL

Your mock server gets a unique URL like:

https://your-mock-id.mock.pstmn.io

Use in requests:

GET https://your-mock-id.mock.pstmn.io/posts/1

API Documentation with Free APIs

Postman auto-generates documentation from collections.

Publishing Documentation for Free APIs Collection

  1. Select “Free APIs Testing Collection”
  2. Click View Documentation (right sidebar)
  3. Click Publish
  4. Configure:
  • Visibility: Public
  • Custom domain (if available)
  1. Click Publish

Adding Descriptions to Requests

For each request:

  1. Open request
  2. Click Documentation tab
  3. Add description:
## Get Single Post

Returns a single post from JSONPlaceholder API.

### URL
`GET https://jsonplaceholder.typicode.com/posts/:id`

### Parameters

| Name | Type   | Required | Description          |
|------|--------|----------|----------------------|
| id   | Number | Yes      | ID of the post to retrieve |

### Response Example

json
{
“userId”: 1,
“id”: 1,
“title”: “sunt aut facere repellat provident occaecati excepturi optio reprehenderit”,
“body”: “quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto”
}

### Test Results
- Status code: 200 OK
- Response time: < 500ms
- Data validation: All fields present and correctly typed

Team Collaboration with Free APIs

Creating a Team Workspace

  1. Click workspace switcher (top-left)
  2. Select Create Workspace
  3. Choose Team
  4. Name: “API Testing Team”
  5. Visibility: Team
  6. Click Create

Sharing Collections

Method 1: Share via Link:

  1. Right-click collection
  2. Select Share Collection
  3. Choose Public visibility
  4. Copy shareable link

Method 2: Invite Team Members:

  1. Click workspace name
  2. Click Invite
  3. Enter team member emails
  4. Permission: Can edit
  5. Click Send Invite

Version Control with Collections

  1. Click collection menu (…)
  2. Select Create Fork
  3. Make changes to forked version
  4. Click Create Pull Request
  5. Team reviews and merges

Newman: CLI Tool for Free API Testing

Newman allows running Postman collections from command line.

Installation

# Using npm (Node.js required)
npm install -g newman

# Using Homebrew (macOS)
brew install newman

# Verify installation
newman --version

Exporting Collection for Newman

  1. In Postman, select collection
  2. Click … menu
  3. Select Export
  4. Choose Collection v2.1
  5. Click Export
  6. Save as free-apis-collection.json

Exporting Environment

  1. Select environment
  2. Click … menu
  3. Select Export
  4. Save as free-apis-environment.json

Basic Newman Commands

# Run collection
newman run free-apis-collection.json

# Run with environment
newman run free-apis-collection.json -e free-apis-environment.json

# Run with iteration count
newman run free-apis-collection.json -n 3

# Run with delay between requests
newman run free-apis-collection.json -d 1000

# Generate HTML report
newman run free-apis-collection.json -r html,cli

# Specify report output
newman run free-apis-collection.json -r html --reporter-html-export report.html

Complete Newman Example

# Run full test suite with reports
newman run free-apis-collection.json \
  -e free-apis-environment.json \
  -d test_data.csv \
  -r cli,html,json,junit \
  --reporter-html-export newman-report.html \
  --reporter-json-export newman-report.json \
  --reporter-junit-export newman-report.xml \
  --delay-request 500

CI/CD Integration Example

GitHub Actions workflow:

name: API Tests
on: [push, pull_request]
jobs:
  api-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Setup Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '16'

      - name: Install Newman
        run: npm install -g newman

      - name: Run API Tests
        run: |
          newman run tests/free-apis-collection.json \
            -e tests/free-apis-environment.json \
            -r cli,html \
            --reporter-html-export newman-report.html

      - name: Upload Test Report
        uses: actions/upload-artifact@v2
        with:
          name: api-test-report
          path: newman-report.html

Advanced Features with Free APIs

Testing Pagination

JSONPlaceholder pagination example:

GET {{jsonplaceholder_url}}/posts
Params:
  _page: 1
  _limit: 10

Tests for pagination:

// Check pagination headers
pm.test("Pagination headers present", function () {
    const linkHeader = pm.response.headers.get("Link");
    const totalCount = pm.response.headers.get("X-Total-Count");

    pm.expect(linkHeader).to.exist;
    pm.expect(totalCount).to.exist;

    // Parse total count
    const total = parseInt(totalCount);
    pm.expect(total).to.be.above(0);

    // Check if we have more pages
    const hasNextPage = linkHeader.includes('rel="next"');
    pm.environment.set("has_next_page", hasNextPage.toString());
});

Testing Rate Limits

Some free APIs have rate limits:

// Check rate limit headers
pm.test("Rate limit headers present", function () {
    const limit = pm.response.headers.get("X-RateLimit-Limit");
    const remaining = pm.response.headers.get("X-RateLimit-Remaining");
    const reset = pm.response.headers.get("X-RateLimit-Reset");

    if (limit) {
        console.log(`Rate limit: ${limit}, Remaining: ${remaining}`);
        pm.environment.set("rate_limit_remaining", remaining);

        // Warn if running low
        if (parseInt(remaining) < 10) {
            console.warn("Rate limit almost reached!");
        }
    }
});

Testing Error Responses

Testing 404 response:

GET {{jsonplaceholder_url}}/posts/99999

Error response tests:

pm.test("404 Not Found", function () {
    pm.response.to.have.status(404);
});

pm.test("Error response structure", function () {
    if (pm.response.code === 404) {
        const response = pm.response.json();
        // Some APIs return error objects, others return empty
        console.log("404 response:", JSON.stringify(response));
    }
});

Best Practices for Free API Testing

Organization Structure

  1. Folder by API Provider:
   Collections/
   ├── JSONPlaceholder/
   ├── ReqRes/
   ├── Public APIs/
   └── Custom APIs/
  1. Request Naming Convention:
  • [METHOD] [Resource] [Action]
  • Example: GET Posts List, POST Create User
  1. Environment Strategy:
  • Development: Local/testing URLs
  • Staging: Staging server URLs
  • Production: Live API URLs

Testing Strategy

  1. Start with Happy Path:
  • Test successful requests first
  • Verify response structure
  • Check data types
  1. Add Edge Cases:
  • Test with invalid data
  • Test with missing parameters
  • Test with extreme values
  1. Performance Testing:
  • Set response time thresholds
  • Monitor performance trends
  • Alert on degradation

Security Considerations

  1. Never Commit Secrets:
  • Use environment variables for API keys
  • Use .gitignore for Postman data files
  • Use Postman’s built-in secret masking
  1. Input Validation:
  • Test SQL injection attempts
  • Test XSS attempts
  • Test path traversal attempts
  1. Authentication Testing:
  • Test with invalid tokens
  • Test expired tokens
  • Test with missing authentication

Common Workflows with Free APIs

Development Workflow

  1. API Exploration:
  • Use free APIs to understand patterns
  • Test different HTTP methods
  • Experiment with various data formats
  1. Prototyping:
  • Use mock servers for frontend development
  • Create example responses
  • Test API contracts
  1. Integration Testing:
  • Test real API integrations
  • Validate data transformations
  • Test error handling

Learning Workflow

  1. Beginner:
  • Start with simple GET requests
  • Understand response formats
  • Learn about HTTP status codes
  1. Intermediate:
  • Add authentication
  • Write basic tests
  • Use environments
  1. Advanced:
  • Create complex test suites
  • Implement CI/CD pipelines
  • Monitor API health

Troubleshooting Common Issues

Request Fails

  1. Check URL:
   // Log URL in pre-request script
   console.log("Request URL:", pm.request.url.toString());
  1. Check Network:
  • Verify internet connection
  • Check proxy settings
  • Test with different API
  1. Check API Status:
  • Test with known working endpoint
  • Check API documentation
  • Verify rate limits

Tests Fail

  1. Check Response Data:
   // Log full response for debugging
   console.log("Response:", pm.response.text());
  1. Check Variable Values:
   // Log all environment variables
   console.log("Environment:", pm.environment.toObject());
  1. Check Test Logic:
  • Simplify test to isolate issue
  • Test with hardcoded values first
  • Check JavaScript syntax

Performance Issues

  1. Collection Optimization:
  • Reduce number of requests
  • Add delays between requests
  • Use parallel execution where possible
  1. Test Optimization:
  • Minimize test execution time
  • Remove redundant tests
  • Use efficient assertions

Migrating from cURL to Postman

Import cURL Commands

  1. Click Import button (top-left)
  2. Select Raw Text tab
  3. Paste cURL command:
   curl -X GET https://jsonplaceholder.typicode.com/posts/1 \
     -H "Content-Type: application/json" \
     -H "X-Custom-Header: TestValue"
  1. Click Continue
  2. Select import as new request
  3. Click Import

cURL to Postman Comparison

cURL:

curl -X POST https://reqres.in/api/users \
  -H "Content-Type: application/json" \
  -d '{"name": "John", "job": "Developer"}'

Postman Equivalent:

  • Method: POST
  • URL: https://reqres.in/api/users
  • Headers: Content-Type: application/json
  • Body (raw JSON):
  {
    "name": "John",
    "job": "Developer"
  }

Postman Pricing for Free Tier

Free Plan Limitations

  • Unlimited collections
  • Up to 3 shared workspaces
  • Basic monitoring (limited runs)
  • Mock servers (limited calls)
  • 3-person team limit
  • 1 monitor with 1000 monthly calls
  • Limited history retention

Free Plan Suitability

The free plan is sufficient for:

  • Individual learning and testing
  • Small project API testing
  • Educational purposes
  • Open source projects
  • Personal API development

Conclusion

Postman provides a comprehensive platform for API testing and development that complements command-line tools like cURL. With its intuitive interface, powerful testing capabilities, and support for the entire API lifecycle, Postman is an essential tool for modern developers.

Key Takeaways

  1. Start Simple: Begin with basic requests to free APIs
  2. Build Gradually: Add tests, environments, and automation step by step
  3. Leverage Free Resources: Use free APIs for practice and learning
  4. Automate Testing: Use collections and Newman for consistent testing
  5. Collaborate: Share collections and work as a team

Next Steps

  1. Practice: Use the free APIs listed to build your skills
  2. Build Portfolio: Create comprehensive test collections
  3. Contribute: Share your collections with the community
  4. Stay Updated: Follow Postman’s blog and updates
  5. Explore Advanced Features: Experiment with mock servers, monitors, and flows

Resources and Further Learning

Official Resources

  • Postman Learning Center: https://learning.postman.com/
  • Postman API Network: https://www.postman.com/explore
  • Postman Blog: https://blog.postman.com/
  • Postman Community: https://community.postman.com/

Free APIs for Practice

  • JSONPlaceholder: https://jsonplaceholder.typicode.com
  • ReqRes: https://reqres.in
  • Public APIs: https://publicapis.dev
  • Any API: https://any-api.com
  • API List: https://apilist.fun

Tutorials and Courses

  • Postman Student Program
  • Postman YouTube Channel
  • FreeCodeCamp API Testing Course
  • Udemy Free Postman Courses

Books

  • “Postman for API Development” by S. R. Prabhu
  • “API Testing and Development with Postman” by Dave Westerveld
  • “Automated API Testing with Postman” by Ravi G

By mastering Postman with free APIs, you’ll develop valuable skills that translate directly to real-world API development and testing scenarios. Start exploring today to build your API testing expertise.

Posts Carousel

Leave a Comment

Your email address will not be published. Required fields are marked with *

Latest Posts

Most Commented

Featured Videos