Skip to main content

API Testing Strategies: Unit, Integration, Contract, and E2E

·APIScout Team
api testingintegration testingcontract testingdeveloper toolsbest practices

API Testing Strategies: Unit, Integration, Contract, and E2E

APIs need four types of tests. Unit tests verify individual functions. Integration tests verify endpoints work correctly. Contract tests verify the API matches its specification. End-to-end tests verify complete workflows. Here's when to use each and which tools to choose.

The API Testing Pyramid

        ╱╲
       ╱ E2E ╲           Few, slow, expensive
      ╱────────╲
     ╱ Contract  ╲       Medium, catch breaking changes
    ╱──────────────╲
   ╱  Integration   ╲    Many, verify endpoints
  ╱──────────────────╲
 ╱      Unit          ╲  Most, fast, cheap
╱──────────────────────╲

Unit Tests

Test individual functions in isolation — validation logic, data transformation, business rules. Mock external dependencies.

What to test:

  • Input validation (does it reject bad data?)
  • Business logic (does the calculation work?)
  • Error handling (does it throw the right error?)
  • Data transformation (does the mapper produce correct output?)

Tools: Jest, Vitest, pytest, Go testing

Example: Test that a price calculation function correctly applies discounts, taxes, and currency conversion — without hitting a database or API.

Integration Tests

Test API endpoints with real (or realistic) dependencies — database, cache, external services. The most important test type for APIs.

What to test:

  • Endpoint returns correct status codes
  • Response body matches expected schema
  • Authentication works (valid/invalid/missing tokens)
  • Authorization works (user A can't access user B's data)
  • Pagination works correctly
  • Error responses are properly formatted
  • Database changes are persisted

Tools: Supertest (Node.js), pytest + httpx (Python), net/http/httptest (Go), REST Assured (Java)

Pattern:

1. Set up test database with seed data
2. Make HTTP request to endpoint
3. Assert status code, response body, headers
4. Assert database state changed correctly
5. Clean up

Contract Tests

Verify your API matches its documented contract (OpenAPI spec). Catch breaking changes before they reach production.

What to test:

  • Response schema matches OpenAPI spec
  • Required fields are present
  • Field types are correct
  • Enum values are valid
  • New endpoints are documented
  • Removed endpoints are deprecated first

Tools:

ToolTypeDescription
PrismMock + validateMock server from OpenAPI, validate requests/responses
DreddContract testingTest real API against OpenAPI/API Blueprint
SchemathesisProperty-basedGenerate test cases from OpenAPI spec
PactConsumer-drivenContracts defined by API consumers
SpectralLintLint OpenAPI specs for design rules

Consumer-Driven Contracts (Pact)

API consumers define what they expect. The API provider verifies against consumer expectations. If the provider changes break a consumer's contract, tests fail before deployment.

End-to-End Tests

Test complete user workflows that span multiple API calls:

1. Create user (POST /users)
2. Login (POST /auth/login)
3. Create order (POST /orders)
4. Process payment (POST /payments)
5. Check order status (GET /orders/123)
6. Verify webhook received

What to test:

  • Complete business workflows
  • Multi-step operations
  • Webhook delivery
  • Async job completion
  • Cross-service interactions

Tools: Playwright (for API + UI), custom scripts, Postman collections, k6 (load + functional)

Warning: E2E tests are slow, flaky, and expensive. Write fewer of them. Test critical paths only (signup, checkout, payment).

Test Environment Strategy

EnvironmentPurposeData
LocalUnit + integration testsIn-memory DB or Docker
CI/CDAll test typesEphemeral test databases
StagingE2E + contractSeed data, sandbox APIs
ProductionSmoke tests onlyReal data, read-only tests

Testing Checklist

Every Endpoint Should Have Tests For:

  • Happy path (valid request → expected response)
  • Authentication (missing, invalid, expired token)
  • Authorization (user accessing other user's data)
  • Validation (missing required fields, invalid types, boundary values)
  • Not found (requesting non-existent resources)
  • Rate limiting (verify 429 is returned)
  • Error response format (consistent error schema)

API-Wide Tests:

  • All endpoints require authentication (no open endpoints by accident)
  • Response schemas match OpenAPI spec
  • CORS headers are correct
  • Security headers are present
  • Rate limit headers are included

Testing APIs? Explore API testing tools and best practices on APIScout — comparisons, guides, and developer resources.

Comments