Home / Insights / QA and Software Testing
QA and Software Testing
An API Testing Strategy from Contracts to Failure Handling
Most API test suites check that valid requests return valid responses. Real failures come from contracts that drift, broken authorisation, duplicate requests on retry and slow dependencies. This guide gives a layered API testing strategy, a test matrix and a worked example of a retry that must not create a duplicate record.
TopicsQA and Software TestingArchitecture and ModernizationWeb and SaaS Development
Key takeaways
- API tests are faster and more stable than UI tests and can start before the front end exists, so they should carry most of your automated coverage.
- A good strategy has layers: contract, functional, authorisation, failure handling, performance and security.
- Test what goes wrong, not only what goes right: invalid input, missing permissions, timeouts, duplicate requests and dependency failures.
- Retried requests that create resources need idempotency, and that needs tests that send the same request twice.
- Run fast tests on every change and slower suites on a schedule, and use production monitoring to find the cases tests missed.
On this page
APIs connect mobile apps to servers, front ends to back ends and companies to their partners. When an API breaks, many clients break at once. Yet API testing is often limited to a collection of requests that check valid inputs return a 200 response. The failures that reach production are usually different: a field renamed without warning, a user who can read another customer’s data by changing an ID, a payment created twice because a client retried a timed-out request.
This guide sets out a layered API testing strategy for product teams, with a test matrix you can adapt and a worked example of the retry problem.
Why test at the API layer
- Speed: API tests run in milliseconds to seconds, so hundreds can run on every change.
- Stability: they do not break when a button moves.
- Early start: they can be written from an API specification before the front end exists.
- Precision: a failing API test points to the service at fault.
API tests do not replace UI tests. They complement them: a few end-to-end UI tests confirm the main journeys, while API tests cover rules, edge cases and failure handling in depth. Our guide to continuous testing explains how these layers fit into a pipeline.
The layers of an API testing strategy
| Layer | What it checks | Typical tools and techniques |
|---|---|---|
| — | — | — |
| Contract | Requests and responses match the agreed specification; changes do not break consumers | OpenAPI schema validation, consumer-driven contract tests |
| Functional | Business rules, validation, state changes, error responses | Automated tests in your language’s HTTP test library or an API client tool |
| Authorisation | Each role and user can access only what they should | Role matrix tests, object-level access tests |
| Failure handling | Timeouts, retries, duplicates, dependency failures, partial failures | Fault injection, mocked dependencies, repeated requests |
| Performance | Latency and throughput under expected and peak load | Load tests with realistic data and traffic mix |
| Security | Common API vulnerabilities, input handling, rate limits | Security test cases, scanners, penetration tests |
| Monitoring | Behaviour in production | Synthetic checks, error rate and latency alerts |
Each layer catches a different class of failure.
Contract tests
If your API has an OpenAPI specification, validate responses against it in every test run. Our guide to self-documenting APIs shows how to keep that specification accurate. For APIs with several consumers, such as a web app, a mobile app and partners, consumer-driven contract tests let each consumer record the fields and behaviours it relies on, and the provider’s pipeline fails when a change would break one of them.
Functional tests
For each endpoint, cover:
- Valid requests with typical and boundary values.
- Invalid input: missing fields, wrong types, values out of range, malformed JSON.
- State transitions: what is allowed from each state and what is rejected.
- Error responses: correct status codes and a consistent, documented error body.
Authorisation tests
Broken object level authorisation is first in the OWASP API Security Top 10 2023. It happens when an API checks that a user is logged in but not that they may access the specific object requested. Test it directly: log in as user A, request user B’s resources by ID and expect a refusal. Build a role matrix and test every role against every sensitive operation.
A test matrix for one endpoint
Here is an illustrative matrix for `POST /quotes`, which creates a quote for a customer in a field-service company’s system.
| Case | Request | Expected result |
|---|---|---|
| — | — | — |
| Valid quote | Sales user, valid customer and lines | 201 Created; quote stored with correct totals |
| Missing customer | No customer ID | 400 with a field error |
| Unknown product | Line references a product not in the price list | 422 with a clear message |
| Discount above limit | 20% discount, sales role | 201 with status Pending approval, not Approved |
| Other company’s customer | Customer ID belonging to another tenant | 404 or 403; no data leaked |
| Technician role | Technician tries to create a quote | 403 |
| No token | Missing authentication | 401 |
| Same request retried | Identical request with the same idempotency key | One quote created; second response returns the original result |
| Same key, different body | Idempotency key reused with changed lines | 422; no new quote |
| Concurrent retry | Second request while the first is still processing | 409 or a wait; never two quotes |
| Price service slow | Price list dependency delayed beyond timeout | Defined error response within the timeout; no partial quote |
| Large quote | 500 lines | Accepted or rejected according to the documented limit |
Illustrative API test matrix. Most cases test what should not happen.
Worked example: a retry that must not create a duplicate
A technician’s tablet submits a quote over a weak connection. The server creates the quote, but the response is lost. The app retries. Without protection, the customer now has two quotes, and later two invoices.
HTTP defines methods such as PUT and DELETE as idempotent: repeating them has the same effect as sending them once. POST is not idempotent by definition, so APIs that create resources need their own mechanism. A common one is an idempotency key: the client generates a unique key for each logical operation and sends it in a header; the server stores the key with the result and returns the stored result when the same key arrives again. An IETF draft specification for an Idempotency-Key header describes this pattern, including recommended errors for a missing key (400), a reused key with a different request (422) and a retry that arrives while the original is still in progress (409).
The tests for this behaviour:
1. Send POST /quotes with Idempotency-Key K1 and body B. Expect 201 and quote ID Q.2. Send the identical request again with K1. Expect the same quote ID Q and no new quote in the database.3. Send POST /quotes with K1 and a changed body B2. Expect 422 and no new quote.4. Send two requests with key K2 at the same time. Expect exactly one quote; the other request receives 409 or the same result.5. Simulate a lost response: create with K3, drop the response, retry with K3. Expect one quote and the original response.These tests belong in the pipeline because the bug they catch is rare in testing and expensive in production.
Testing dependencies and failures
Most APIs call other services: databases, payment providers, price services, email. Test how your API behaves when they misbehave:
- Timeouts: the dependency responds slowly. Your API should fail within its own timeout with a clear error.
- Errors: the dependency returns a 500. Your API should not leave half-completed state.
- Unexpected data: the dependency returns a field you did not expect, or omits one you need.
- Recovery: after the dependency recovers, retries and queued work complete correctly.
Use mocks or service virtualisation for repeatable tests, and controlled chaos experiments in staging to check the real behaviour.
Performance and security
Performance tests for APIs should use a realistic mix of operations and data sizes, not a single endpoint hammered in isolation. Our load testing guide covers planning and analysis.
For security, use the OWASP API Security Top 10 2023 as a checklist:
| Risk | Test idea |
|---|---|
| — | — |
| API1 Broken object level authorisation | Access another user’s or tenant’s objects by ID |
| API2 Broken authentication | Expired, malformed and reused tokens |
| API3 Broken object property level authorisation | Read or write fields the role should not see or change |
| API4 Unrestricted resource consumption | Large payloads, high request rates, expensive queries |
| API5 Broken function level authorisation | Call admin operations as a normal user |
| API6 Unrestricted access to sensitive business flows | Automate a flow such as sign-up or booking at scale |
| API7 Server side request forgery | Submit internal URLs where the API fetches remote resources |
| API8 Security misconfiguration | Verbose errors, permissive CORS, missing security headers |
| API9 Improper inventory management | Old or undocumented API versions still reachable |
| API10 Unsafe consumption of APIs | Malicious or malformed responses from third-party APIs |
The ten risks in the OWASP API Security Top 10 2023, with example test ideas.
Fitting tests into delivery
| When | What runs |
|---|---|
| — | — |
| Every commit | Unit tests, contract validation, fast functional and authorisation tests |
| Every merge to main | Full functional suite, idempotency and failure tests with mocks |
| Nightly or before release | Integration tests with real sandboxes, performance smoke tests, security scans |
| Before major releases | Full load tests, penetration tests |
| In production | Synthetic checks on key endpoints, alerts on error rates and latency |
Fast feedback on every change; deeper checks on a schedule.
Choosing tools
Choose tools that fit your team rather than the longest feature list. Teams with developers writing tests often prefer test libraries in their own language, which keeps tests in the same repository and review process. Teams with dedicated QA may prefer an API client tool with a command-line runner for pipelines. Whatever you choose, make sure tests run headless in CI, read configuration from the environment and produce reports your team will actually read.
Frequently asked questions
How many API tests do we need?
Enough to cover each endpoint’s rules, each role’s permissions and the failure cases that matter. Focus on risk: payment, personal data and partner integrations deserve the deepest coverage.
Should developers or testers write API tests?
Both. Developers usually write tests alongside the code; QA designs the matrix, adds negative and cross-cutting cases and owns the overall strategy.
What is the difference between contract and integration testing?
Contract tests check that each side honours the agreed interface, usually without running both together. Integration tests run the real services together to check they work as a whole.
Do internal APIs need security testing?
Yes. Internal APIs are often reachable from more places than expected, and attackers who gain a foothold use them.
Sources and methodology
Facts in this article were checked against the sources below. Directory data (ratings, review counts, rate bands and team sizes) changes over time and is shown as published on the date accessed. Illustrative examples are labelled as such and are not quotes.
- OWASP: API Security Top 10 2023 — List of the ten API security risks used in the checklist
- IETF: The Idempotency-Key HTTP Header Field (Internet-Draft, draft-07, October 2025) — Draft specification; recommended 400, 422 and 409 responses for idempotency errors
- AltexSoft: API Testing Approaches and Tools — Reviewed as a baseline; covers test types and tools without idempotency or contract testing
- Netguru: API Testing Tools — Reviewed as a baseline; tool-focused overview
Related reading
Continue your research
Want API tests that catch real production failures?
Share your APIs and current tests. We will help you design a layered strategy with contract, authorisation and failure-handling tests in your pipeline.
