Перейти к основному содержаниюПерейти к основному содержимому
OnlineDevTools
/

API Testing Workflow: Complete Guide

Master the art of API testing with professional workflows, tools, and best practices. From basic REST endpoints to complex GraphQL queries and WebSocket connections, this guide covers everything you need to test APIs effectively.

Why API Testing Matters

API testing is fundamental to modern software development. Unlike UI testing, which can be brittle and slow, API testing provides fast, reliable feedback about application functionality. APIs are the backbone of modern applications, and robust API testing ensures reliability, security, and performance.

Key Benefits of API Testing

  • Early bug detection: Find issues before UI development begins
  • Faster execution: API tests run 10-100x faster than UI tests
  • Better coverage: Test edge cases and error conditions easily
  • Independent testing: No dependency on UI completion
  • Contract validation: Ensure API contracts are maintained across versions
  • Security testing: Validate authentication, authorization, and input validation

When to Test APIs

  • During development: Test endpoints as you build them
  • Before deployment: Validate all endpoints work correctly
  • After deployment: Monitor production APIs for health
  • During integration: Test third-party API integrations
  • Version changes: Ensure backward compatibility

Types of APIs to Test

1. REST APIs

REST (Representational State Transfer) is the most common API architecture. RESTful APIs use HTTP methods (GET, POST, PUT, DELETE) and standard status codes.

Characteristics:

  • Resource-based URLs: /api/users/123
  • HTTP methods define actions: GET (read), POST (create), PUT (update), DELETE (remove)
  • Stateless communication
  • JSON or XML responses

2. GraphQL APIs

GraphQL provides a query language for APIs, allowing clients to request exactly the data they need. Unlike REST, GraphQL uses a single endpoint and flexible queries.

Key differences from REST:

  • Single endpoint (usually /graphql)
  • Client defines response structure
  • No over-fetching or under-fetching
  • Strong typing with schema

3. WebSocket APIs

WebSockets enable bi-directional, real-time communication between client and server. Perfect for chat applications, live updates, and streaming data.

Use cases:

  • Real-time chat and messaging
  • Live sports scores or stock prices
  • Collaborative editing (like Google Docs)
  • Gaming and multiplayer interactions

4. SOAP APIs

SOAP (Simple Object Access Protocol) is an older protocol using XML for structured messages. Still common in enterprise and legacy systems.

Essential API Testing Tools

1. API Tester

The API Tester is your Swiss Army knife for testing REST endpoints. It supports all HTTP methods, custom headers, and various authentication schemes.

Key features:

  • Test GET, POST, PUT, PATCH, DELETE requests
  • Add custom headers (Authorization, Content-Type, etc.)
  • Send JSON, form data, or raw body content
  • View response headers, status codes, and timing
  • Save and replay requests

2. GraphQL Playground

The GraphQL Playground provides a powerful IDE for testing GraphQL queries and mutations with schema introspection.

What makes it powerful:

  • Auto-completion based on schema
  • Schema documentation sidebar
  • Query history and variables support
  • Multiple tabs for different queries

3. WebSocket Tester

The WebSocket Tester lets you establish WebSocket connections, send messages, and monitor bi-directional communication.

4. JWT Debugger

The JWT Debugger decodes and validates JSON Web Tokens, essential for testing authenticated APIs.

5. Curl Generator

The Curl Generator creates curl commands from your API requests, perfect for documentation and sharing with team members.

REST API Testing

Testing Different HTTP Methods

GET Requests - Reading Data

GET requests should be idempotent (multiple calls produce same result) and never modify data.

GET /api/users/123
Headers:
  Accept: application/json
  Authorization: Bearer <token>

Expected Response (200):
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com"
}

What to test:

  • Status code 200 for successful retrieval
  • Status code 404 for non-existent resources
  • Response body matches expected structure
  • Response time is acceptable (< 500ms for simple queries)

POST Requests - Creating Resources

POST creates new resources and should return 201 Created with location header.

POST /api/users
Headers:
  Content-Type: application/json
  Authorization: Bearer <token>
Body:
{
  "name": "Jane Smith",
  "email": "jane@example.com",
  "role": "developer"
}

Expected Response (201):
{
  "id": 124,
  "name": "Jane Smith",
  "email": "jane@example.com",
  "role": "developer",
  "createdAt": "2026-01-20T10:30:00Z"
}

Headers:
  Location: /api/users/124

What to test:

  • Status code 201 for successful creation
  • Response includes newly created resource with ID
  • Location header points to new resource
  • Validation errors return 400 Bad Request
  • Duplicate detection returns 409 Conflict (if applicable)

PUT/PATCH Requests - Updating Resources

PUT replaces entire resource, PATCH updates specific fields.

PATCH /api/users/124
Headers:
  Content-Type: application/json
  Authorization: Bearer <token>
Body:
{
  "role": "senior-developer"
}

Expected Response (200):
{
  "id": 124,
  "name": "Jane Smith",
  "email": "jane@example.com",
  "role": "senior-developer",
  "updatedAt": "2026-01-20T11:00:00Z"
}

DELETE Requests - Removing Resources

DELETE removes resources and should be idempotent.

DELETE /api/users/124
Headers:
  Authorization: Bearer <token>

Expected Response (204):
(No content)

OR (200):
{
  "message": "User deleted successfully",
  "deletedId": 124
}

Testing Query Parameters

Query parameters filter, sort, and paginate results:

GET /api/users?role=developer&limit=10&offset=20&sort=name

Tests:
✓ Filtering works correctly
✓ Pagination returns correct subset
✓ Sorting is applied
✓ Invalid parameters return 400

GraphQL Testing

Query Testing

GraphQL queries retrieve data with flexible field selection:

query GetUser($userId: ID!) {
  user(id: $userId) {
    id
    name
    email
    posts {
      id
      title
      createdAt
    }
  }
}

Variables:
{
  "userId": "123"
}

Expected Response:
{
  "data": {
    "user": {
      "id": "123",
      "name": "John Doe",
      "email": "john@example.com",
      "posts": [
        {
          "id": "1",
          "title": "First Post",
          "createdAt": "2026-01-15T10:00:00Z"
        }
      ]
    }
  }
}

Mutation Testing

Mutations modify data in GraphQL:

mutation CreatePost($input: CreatePostInput!) {
  createPost(input: $input) {
    id
    title
    content
    author {
      id
      name
    }
  }
}

Variables:
{
  "input": {
    "title": "New Post",
    "content": "Post content here",
    "authorId": "123"
  }
}

GraphQL Testing Best Practices

  • Test queries with different field combinations
  • Validate error handling for invalid queries
  • Test with and without variables
  • Verify schema changes don't break existing queries
  • Test authorization on field-level permissions

WebSocket Testing

Establishing Connection

WebSocket testing starts with establishing a connection:

ws://localhost:3000/socket
OR
wss://api.example.com/socket (secure)

Connection Events:
- onopen: Connection established
- onmessage: Receive messages
- onerror: Handle errors
- onclose: Connection closed

Testing Message Flow

Test both client-to-server and server-to-client messages:

Send (Client → Server):
{
  "type": "chat.message",
  "content": "Hello, world!",
  "channelId": "general"
}

Receive (Server → Client):
{
  "type": "chat.message",
  "messageId": "msg-123",
  "content": "Hello, world!",
  "author": "John Doe",
  "timestamp": "2026-01-20T12:00:00Z"
}

WebSocket Testing Checklist

  • ✓ Connection establishes successfully
  • ✓ Authentication works (if required)
  • ✓ Messages sent from client reach server
  • ✓ Messages from server are received
  • ✓ Reconnection works after disconnect
  • ✓ Ping/pong keep-alive works
  • ✓ Error messages are handled gracefully

Authentication & Security Testing

Bearer Token Authentication

Most modern APIs use Bearer tokens (JWT):

Headers:
  Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Tests:
✓ Valid token grants access (200)
✓ Invalid token returns 401 Unauthorized
✓ Expired token returns 401
✓ Missing token returns 401
✓ Token with wrong signature returns 401

API Key Authentication

Headers:
  X-API-Key: abc123def456

OR Query Parameter:
  /api/users?api_key=abc123def456

OAuth 2.0 Testing

Test OAuth flows with the OAuth Playground:

  • Authorization code flow
  • Client credentials flow
  • Refresh token flow
  • Token expiration handling

Security Testing Checklist

  • ✓ Test with valid credentials → 200 OK
  • ✓ Test with invalid credentials → 401 Unauthorized
  • ✓ Test without credentials → 401 Unauthorized
  • ✓ Test with expired tokens → 401 Unauthorized
  • ✓ Test authorization (can user access this resource?) → 403 Forbidden
  • ✓ Test CORS headers for browser security
  • ✓ Test rate limiting → 429 Too Many Requests

Response Validation

Status Code Validation

HTTP status codes indicate request outcome:

  • 200 OK: Successful GET, PUT, PATCH
  • 201 Created: Successful POST (resource created)
  • 204 No Content: Successful DELETE (no body returned)
  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Authentication required or failed
  • 403 Forbidden: Authenticated but not authorized
  • 404 Not Found: Resource doesn't exist
  • 409 Conflict: Duplicate or conflicting resource
  • 422 Unprocessable Entity: Validation errors
  • 500 Internal Server Error: Server-side error

Response Body Validation

Use JSON Validator to verify response structure:

Expected structure:
{
  "id": "string",
  "name": "string",
  "email": "string (valid email format)",
  "createdAt": "string (ISO 8601 date)",
  "role": "enum: user|admin|developer"
}

Validation checks:
✓ All required fields present
✓ Field types match specification
✓ Date formats are valid
✓ Email format is valid
✓ Enum values are from allowed list
✓ No unexpected extra fields (if strict)

Header Validation

Important headers to validate:

  • Content-Type: application/json - Correct content type
  • Cache-Control - Caching directives
  • ETag - Resource version for caching
  • Location - URL of newly created resource (201 responses)
  • X-Rate-Limit-* - Rate limiting information

Professional Testing Workflows

Development Workflow

  1. Design API contract: Define endpoints, methods, request/response formats
  2. Create test cases: Write tests before implementation (TDD)
  3. Implement endpoint: Build the API functionality
  4. Test manually: Use API Tester for quick validation
  5. Automate tests: Write automated tests for CI/CD
  6. Document: Generate API documentation with examples

Integration Testing Workflow

Testing third-party API integrations:

  1. Read API documentation: Understand endpoints, authentication, rate limits
  2. Get API credentials: Obtain test and production keys
  3. Test in sandbox: Use test environment first
  4. Handle errors gracefully: Test all error scenarios
  5. Implement retry logic: Handle transient failures
  6. Monitor in production: Set up alerts for failures

Pre-Deployment Checklist

  • ✓ All endpoints tested with valid inputs
  • ✓ All error scenarios tested (400, 401, 404, 500)
  • ✓ Authentication and authorization working
  • ✓ Rate limiting tested
  • ✓ CORS headers configured correctly
  • ✓ Response times acceptable (< 1s for most endpoints)
  • ✓ API documentation updated
  • ✓ Security headers present (HTTPS, HSTS, etc.)

Test Automation

Converting Manual Tests to Automation

Use the Curl Generator to create command-line tests:

curl -X POST 'https://api.example.com/users' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <token>' \
  -d '{
    "name": "Jane Smith",
    "email": "jane@example.com"
  }'

Postman Collection Generation

Use the Postman Generator to create importable collections for team sharing.

CI/CD Integration

Integrate API tests into your deployment pipeline:

  • Run tests on every commit
  • Block deployment if tests fail
  • Test against staging environment before production
  • Run smoke tests in production after deployment

Common Issues & Solutions

Problem: CORS Errors in Browser

Symptom: "Access to fetch blocked by CORS policy"

Solution:

  • Test API from server-side or curl (CORS is browser-only)
  • Use CORS Tester to verify headers
  • Ensure server sends correct Access-Control-Allow-Origin header
  • For credentials, server must send Access-Control-Allow-Credentials: true

Problem: 401 Unauthorized with Valid Token

Possible causes:

  • Token expired (check exp claim with JWT Debugger)
  • Wrong header format (should be Bearer <token>, not just token)
  • Token for wrong environment (staging token on production API)
  • Server clock skew (token not yet valid)

Problem: Slow API Responses

Debugging steps:

  1. Check response time in API tester
  2. Test from different locations (latency vs server performance)
  3. Check if specific endpoints are slow (database queries?)
  4. Monitor server logs for slow queries
  5. Consider caching for frequently accessed data

Problem: Inconsistent Test Results

Common causes:

  • Tests modifying shared data (use isolated test data)
  • Race conditions in async operations
  • Cache returning stale data
  • Time-dependent tests (use fixed timestamps in tests)

Related Tools

Summary

Effective API testing requires understanding different API types (REST, GraphQL, WebSocket), using the right tools for each scenario, and following professional workflows. Start with manual testing to understand the API, then automate tests for CI/CD integration.

Remember: Test early, test often, and test thoroughly. APIs are the foundation of modern applications, and robust testing ensures reliability, security, and performance.