Skip to content

Postman API Testing

Comprehensive Postman shortcuts and workflows for API development and testing.

Basic Navigation

ShortcutDescription
Ctrl+NNew Request
Ctrl+Shift+NNew Collection
Ctrl+OOpen
Ctrl+SSave
Ctrl+Shift+SSave As
Ctrl+EnterSend Request
Ctrl+RReload
Ctrl+WClose Tab
Ctrl+Shift+WClose All Tabs
Ctrl+TNew Tab
Ctrl+Shift+TReopen Closed Tab

Request Management

ShortcutDescription
Ctrl+LFocus URL Bar
Ctrl+MChange HTTP Method
Ctrl+Shift+POpen Command Palette
Ctrl+KSearch Collections
Ctrl+HShow/Hide Sidebar
Ctrl+Alt+COpen Console
Ctrl+Alt+EOpen Environment Quick Look

Text Editing

ShortcutDescription
Ctrl+ASelect All
Ctrl+CCopy
Ctrl+VPaste
Ctrl+XCut
Ctrl+ZUndo
Ctrl+YRedo
Ctrl+FFind
Ctrl+GFind Next
Ctrl+Shift+GFind Previous
F3Find Next
Shift+F3Find Previous

Environment and Variables

ShortcutDescription
Ctrl+Alt+EEnvironment Quick Look
Ctrl+Shift+EManage Environments
Variable Syntax
pm.environment.get("var")Get Environment Variable
pm.environment.set("var", "value")Set Environment Variable
pm.globals.get("var")Get Global Variable
pm.globals.set("var", "value")Set Global Variable

HTTP Methods and Status Codes

Common HTTP Methods

MethodPurposeExample
GETRetrieve dataGet user profile
POSTCreate new resourceCreate new user
PUTUpdate entire resourceUpdate user profile
PATCHPartial updateUpdate user email
DELETERemove resourceDelete user account
HEADGet headers onlyCheck if resource exists
OPTIONSGet allowed methodsCORS preflight

HTTP Status Codes

Code RangeTypeCommon Codes
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Moved, 302 Found, 304 Not Modified
4xxClient Error400 Bad Request, 401 Unauthorized, 404 Not Found
5xxServer Error500 Internal Error, 502 Bad Gateway, 503 Unavailable

Pre-request Scripts

Common Pre-request Script Examples

javascript
// Set timestamp
pm.environment.set("timestamp", Date.now());

// Generate random data
pm.environment.set("randomEmail", 
  "user" + Math.random().toString(36).substring(7) + "@example.com");

// Set authentication token
const token = pm.environment.get("auth_token");
pm.request.headers.add({
  key: "Authorization",
  value: "Bearer " + token
});

// Generate UUID
const uuid = require('uuid');
pm.environment.set("requestId", uuid.v4());

// Base64 encode credentials
const username = pm.environment.get("username");
const password = pm.environment.get("password");
const credentials = btoa(username + ":" + password);
pm.environment.set("basicAuth", credentials);

Test Scripts

Basic Assertions

javascript
// Status code tests
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Status code name has string", function () {
    pm.response.to.have.status("OK");
});

// Response time test
pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});

// Header tests
pm.test("Content-Type 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");
});

JSON Response Tests

javascript
// Parse JSON response
const responseJson = pm.response.json();

// Test JSON structure
pm.test("Response has required fields", function () {
    pm.expect(responseJson).to.have.property("id");
    pm.expect(responseJson).to.have.property("name");
    pm.expect(responseJson).to.have.property("email");
});

// Test specific values
pm.test("User ID is correct", function () {
    pm.expect(responseJson.id).to.eql(123);
});

pm.test("Email format is valid", function () {
    pm.expect(responseJson.email).to.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);
});

// Test array responses
pm.test("Response is an array", function () {
    pm.expect(responseJson).to.be.an('array');
});

pm.test("Array has correct length", function () {
    pm.expect(responseJson).to.have.lengthOf(5);
});

Variable Extraction

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

// Set environment variables
pm.environment.set("userId", responseJson.id);
pm.environment.set("userToken", responseJson.token);

// Extract from headers
const location = pm.response.headers.get("Location");
pm.environment.set("resourceUrl", location);

// Extract using regex
const responseText = pm.response.text();
const match = responseText.match(/token:\s*"([^"]+)"/);
if (match) {
    pm.environment.set("extractedToken", match[1]);
}

Collection Runner

Running Collections

javascript
// Collection variables
pm.collectionVariables.set("baseUrl", "https://api.example.com");
pm.collectionVariables.get("baseUrl");

// Data-driven testing
// Use CSV or JSON files for test data
// Access data using pm.iterationData.get("fieldName")

// Workflow control
postman.setNextRequest("Request Name");
postman.setNextRequest(null); // Stop execution

Authentication Workflows

Bearer Token

javascript
// Pre-request script for login
pm.sendRequest({
    url: pm.environment.get("baseUrl") + "/auth/login",
    method: "POST",
    header: {
        "Content-Type": "application/json"
    },
    body: {
        mode: "raw",
        raw: JSON.stringify({
            username: pm.environment.get("username"),
            password: pm.environment.get("password")
        })
    }
}, function (err, response) {
    if (response.code === 200) {
        const token = response.json().token;
        pm.environment.set("authToken", token);
    }
});

OAuth 2.0

javascript
// OAuth 2.0 configuration
const clientId = pm.environment.get("clientId");
const clientSecret = pm.environment.get("clientSecret");
const tokenUrl = pm.environment.get("tokenUrl");

pm.sendRequest({
    url: tokenUrl,
    method: "POST",
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: {
        mode: "urlencoded",
        urlencoded: [
            {key: "grant_type", value: "client_credentials"},
            {key: "client_id", value: clientId},
            {key: "client_secret", value: clientSecret}
        ]
    }
}, function (err, response) {
    if (response.code === 200) {
        const accessToken = response.json().access_token;
        pm.environment.set("accessToken", accessToken);
    }
});

API Testing Workflows

CRUD Operations Testing

javascript
// 1. Create Resource (POST)
pm.test("Create user successfully", function () {
    pm.response.to.have.status(201);
    const user = pm.response.json();
    pm.environment.set("createdUserId", user.id);
});

// 2. Read Resource (GET)
pm.test("Get user successfully", function () {
    pm.response.to.have.status(200);
    const user = pm.response.json();
    pm.expect(user.id).to.eql(pm.environment.get("createdUserId"));
});

// 3. Update Resource (PUT/PATCH)
pm.test("Update user successfully", function () {
    pm.response.to.have.status(200);
});

// 4. Delete Resource (DELETE)
pm.test("Delete user successfully", function () {
    pm.response.to.have.status(204);
});

Error Handling Tests

javascript
// Test error responses
pm.test("Returns 400 for invalid data", function () {
    pm.response.to.have.status(400);
    const error = pm.response.json();
    pm.expect(error).to.have.property("message");
});

pm.test("Returns 401 for unauthorized access", function () {
    pm.response.to.have.status(401);
});

pm.test("Returns 404 for non-existent resource", function () {
    pm.response.to.have.status(404);
});

Best Practices

Organization

  • Use collections to group related requests
  • Create folders within collections for logical grouping
  • Use descriptive names for requests and collections
  • Document APIs using collection descriptions
  • Use environment variables for different stages (dev, staging, prod)

Testing Strategy

  • Write comprehensive test scripts
  • Test both positive and negative scenarios
  • Validate response structure and data types
  • Check response times and performance
  • Test error handling and edge cases

Data Management

  • Use environment variables for configuration
  • Implement data-driven testing with CSV/JSON files
  • Clean up test data after test execution
  • Use dynamic variables for unique test data
  • Separate test data from production data

Collaboration

  • Share collections with team members
  • Use version control for collection exports
  • Document API changes and test updates
  • Create reusable test scripts and snippets
  • Establish naming conventions and standards