Build a comprehensive API integration test suite that validates endpoint behavior, request/response contracts, error handling, authentication flows, and data integrity across your entire API surface with organized test structure and CI/CD integration.
## ROLE
You are a backend engineering lead specializing in API quality and test infrastructure. You have built integration test suites for APIs serving millions of requests daily across REST, GraphQL, gRPC, and WebSocket protocols. You have designed test architectures that run hundreds of API tests in under 5 minutes, catch contract violations before they reach consumers, and serve as living documentation of API behavior. You have deep experience with supertest, Playwright API testing, REST Assured, pytest + httpx, Postman/Newman, and custom test harnesses. You understand the nuances of testing authenticated endpoints, handling database state in integration tests, mocking external dependencies while keeping internal integrations real, and building tests that are fast, reliable, and maintainable.
## OBJECTIVE
Build a complete API integration test suite for [API NAME], a [API TYPE: REST API / GraphQL API / gRPC API / mixed protocol API] built with [TECH STACK: e.g., Node.js + Express + Prisma + PostgreSQL / Go + Gin + GORM + MySQL / Python + FastAPI + SQLAlchemy + PostgreSQL / Java + Spring Boot + JPA + PostgreSQL]. The API has [ENDPOINT COUNT: e.g., 30-50] endpoints organized into [RESOURCE GROUPS: e.g., Users, Products, Orders, Payments, Notifications] with [AUTH TYPE: JWT / OAuth 2.0 / API keys / session-based / multi-auth]. The current integration test situation is [CURRENT STATE: no integration tests / scattered tests without structure / Postman collections only / needs modernization].
## TASK: COMPLETE API INTEGRATION TEST SUITE
### Step 1 — Test Architecture & Project Structure
Design the test project structure that scales from 10 to 1,000+ test cases. Define the directory layout:
```
/tests/integration/
/setup/ — database setup, server bootstrap, auth helpers
/helpers/ — request builders, assertion helpers, data factories
/resources/
/users/ — user endpoint tests
/products/ — product endpoint tests
/orders/ — order endpoint tests
/flows/ — multi-endpoint flow tests
/contracts/ — schema validation tests
```
Configure the test runner for [TEST FRAMEWORK: Jest / Vitest / pytest / JUnit / Go testing] with integration test-specific settings: longer timeouts than unit tests, sequential execution for tests that share database state (or parallel with isolated schemas), and separate configuration files so integration tests can be run independently of unit tests. Set up the test server: show how to bootstrap the application in test mode — either starting the actual server on a random port, using supertest/httpx with the app instance directly, or pointing tests at a deployed staging instance. Configure the test database: create a dedicated test database, run migrations before the suite, and implement the cleanup strategy (transaction rollback per test for speed, or truncation between tests for accuracy with triggers/constraints).
### Step 2 — Authentication & Authorization Test Helpers
Build reusable authentication helpers that eliminate boilerplate from every test. For [AUTH TYPE], create helper functions: `getAuthToken(role)` that generates valid tokens for different user roles (admin, regular user, read-only, service account), `getExpiredToken()` for testing token expiration handling, `getInvalidToken()` for testing invalid signature handling, and `withAuth(request, token)` that attaches the auth header to any request. Write the foundational auth test cases that every API needs:
Auth Test 1 — Unauthenticated access: verify every protected endpoint returns 401 when no auth token is provided, with a consistent error response body. Auth Test 2 — Invalid token: verify endpoints return 401 with a clear error message when the token is malformed or has an invalid signature. Auth Test 3 — Expired token: verify endpoints return 401 (not 500) when the token is expired, with a response that tells the client to refresh. Auth Test 4 — Insufficient permissions: verify endpoints return 403 when a valid user accesses a resource they do not own or an admin-only endpoint. Auth Test 5 — Role-based access matrix: create a test matrix that maps every endpoint to every role and verifies the expected status code (200/201 for allowed, 403 for forbidden).
Show how to generate the role-access matrix test dynamically from a configuration object so that adding a new endpoint automatically tests it against all roles.
### Step 3 — CRUD Endpoint Test Patterns
Write comprehensive test cases for standard CRUD operations following a consistent pattern for every resource. For [PRIMARY RESOURCE: e.g., /api/v1/products]:
CREATE (POST) tests: (1) successful creation with all required fields returns 201 and the created resource with server-generated fields (id, timestamps), (2) creation with all optional fields populated, (3) validation failures — missing required fields return 400 with field-specific error messages, (4) invalid field types (string where number expected) return 400, (5) duplicate unique fields (email, slug) return 409, (6) maximum field length boundaries, (7) creation with nested/related entities, (8) verify the resource actually exists in the database after creation.
READ (GET) tests: (1) get by ID returns 200 with complete resource representation, (2) get non-existent ID returns 404 with clear message, (3) list endpoint returns paginated results with correct total count, (4) list with filter parameters returns correctly filtered results, (5) list with sort parameters returns correctly ordered results, (6) list with search/query parameter, (7) list pagination edge cases (page beyond total, page size of 1, page size of max), (8) field selection/sparse fieldsets if supported, (9) relationship expansion/includes if supported.
UPDATE (PUT/PATCH) tests: (1) full update with PUT replaces all fields, (2) partial update with PATCH modifies only provided fields, (3) update non-existent resource returns 404, (4) update with invalid data returns 400 with validation errors, (5) optimistic concurrency (if implemented) — update with stale version returns 409, (6) update protected fields (id, created_at) is rejected or ignored, (7) verify the database reflects the update.
DELETE tests: (1) delete existing resource returns 204, (2) delete non-existent resource returns 404, (3) delete resource with dependencies — either cascades or returns 409 with explanation, (4) verify the resource is actually removed (or soft-deleted), (5) verify subsequent GET returns 404.
### Step 4 — Error Handling & Edge Case Tests
Test the error handling paths that are often the source of production incidents. Write tests for: malformed JSON request bodies (should return 400, not 500), extremely large request bodies (should be rejected by size limit), SQL injection attempts in query parameters and request bodies (should be sanitized or rejected), XSS payloads in string fields (should be stored safely or rejected), deeply nested JSON objects (should be rejected beyond a depth limit), request with extra/unknown fields (should be ignored or rejected based on API design), concurrent modifications to the same resource (should handle race conditions gracefully), requests with special characters in path parameters (URL encoding, unicode), empty string vs null vs missing field distinction, and numeric overflow values (e.g., quantity of 9999999999). For each error case, verify: (1) the response status code is appropriate (4xx, not 5xx), (2) the error response body follows a consistent schema with error code, message, and details, (3) no sensitive information (stack traces, SQL queries, internal paths) is leaked in error responses, and (4) the error is properly logged for debugging.
### Step 5 — Multi-Endpoint Flow Tests
Write integration tests that validate multi-step business flows spanning multiple endpoints. These tests catch issues that single-endpoint tests miss — incorrect state transitions, data consistency across resources, and side effect failures.
Flow 1 — [PRIMARY BUSINESS FLOW: e.g., Complete Purchase Flow]: Register user → verify email → browse products → add to cart → apply discount code → checkout → process payment → confirm order → check order status → receive notification. Assert the state of every involved resource at each step and verify that the final state is consistent across all related entities.
Flow 2 — [SECONDARY FLOW: e.g., Account Management Flow]: Create account → update profile → upload avatar → change password → enable 2FA → generate API key → revoke API key → deactivate account. Verify that each step's side effects are visible in subsequent steps.
Flow 3 — [ERROR RECOVERY FLOW: e.g., Failed Payment Recovery]: Start checkout → payment fails → retry with different method → payment succeeds → verify order is not duplicated, payment records are correct, and inventory was reserved only once.
For each flow test, use a linear test structure (not dependent test steps) so that any failure produces a clear error message indicating which step failed and what the state was at that point.
### Step 6 — Contract Validation & CI/CD Integration
Implement API contract validation and integrate the entire suite into CI/CD. For contract testing, validate every response against the API schema: if you have an OpenAPI/Swagger spec, use a schema validator to verify every test response matches the documented schema — this catches undocumented fields, missing fields, and type mismatches. Show the schema validation setup for [TECH STACK] and how to fail tests when the response does not match the spec. For response time assertions, add soft performance checks to integration tests: `expect(response.time).toBeLessThan(500)` to catch severe performance regressions (not a replacement for proper performance testing, but a useful early warning).
Build the CI/CD pipeline configuration for [CI/CD TOOL]: (1) start the test database (Docker service or testcontainers), (2) run database migrations, (3) start the API server in test mode, (4) execute integration tests with JUnit-compatible output, (5) collect code coverage for integration-tested code paths, (6) publish test results and coverage as PR artifacts. Show how to run integration tests in parallel safely: either use database transactions for isolation (fastest), create isolated schemas per test worker, or use test-level data namespacing. Configure the suite to run in under [TIME TARGET: 5 minutes] by parallelizing across [WORKER COUNT: 4-8] workers and optimizing database operations (batch inserts, connection pooling).Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[API NAME][AUTH TYPE][TECH STACK]