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.

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

LayerWhat it checksTypical tools and techniques
———
ContractRequests and responses match the agreed specification; changes do not break consumersOpenAPI schema validation, consumer-driven contract tests
FunctionalBusiness rules, validation, state changes, error responsesAutomated tests in your language’s HTTP test library or an API client tool
AuthorisationEach role and user can access only what they shouldRole matrix tests, object-level access tests
Failure handlingTimeouts, retries, duplicates, dependency failures, partial failuresFault injection, mocked dependencies, repeated requests
PerformanceLatency and throughput under expected and peak loadLoad tests with realistic data and traffic mix
SecurityCommon API vulnerabilities, input handling, rate limitsSecurity test cases, scanners, penetration tests
MonitoringBehaviour in productionSynthetic 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.

CaseRequestExpected result
———
Valid quoteSales user, valid customer and lines201 Created; quote stored with correct totals
Missing customerNo customer ID400 with a field error
Unknown productLine references a product not in the price list422 with a clear message
Discount above limit20% discount, sales role201 with status Pending approval, not Approved
Other company’s customerCustomer ID belonging to another tenant404 or 403; no data leaked
Technician roleTechnician tries to create a quote403
No tokenMissing authentication401
Same request retriedIdentical request with the same idempotency keyOne quote created; second response returns the original result
Same key, different bodyIdempotency key reused with changed lines422; no new quote
Concurrent retrySecond request while the first is still processing409 or a wait; never two quotes
Price service slowPrice list dependency delayed beyond timeoutDefined error response within the timeout; no partial quote
Large quote500 linesAccepted 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:

RiskTest idea
——
API1 Broken object level authorisationAccess another user’s or tenant’s objects by ID
API2 Broken authenticationExpired, malformed and reused tokens
API3 Broken object property level authorisationRead or write fields the role should not see or change
API4 Unrestricted resource consumptionLarge payloads, high request rates, expensive queries
API5 Broken function level authorisationCall admin operations as a normal user
API6 Unrestricted access to sensitive business flowsAutomate a flow such as sign-up or booking at scale
API7 Server side request forgerySubmit internal URLs where the API fetches remote resources
API8 Security misconfigurationVerbose errors, permissive CORS, missing security headers
API9 Improper inventory managementOld or undocumented API versions still reachable
API10 Unsafe consumption of APIsMalicious 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

WhenWhat runs
——
Every commitUnit tests, contract validation, fast functional and authorisation tests
Every merge to mainFull functional suite, idempotency and failure tests with mocks
Nightly or before releaseIntegration tests with real sandboxes, performance smoke tests, security scans
Before major releasesFull load tests, penetration tests
In productionSynthetic 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.

  1. OWASP: API Security Top 10 2023 — List of the ten API security risks used in the checklist
  2. IETF: The Idempotency-Key HTTP Header Field (Internet-Draft, draft-07, October 2025) — Draft specification; recommended 400, 422 and 409 responses for idempotency errors
  3. AltexSoft: API Testing Approaches and Tools — Reviewed as a baseline; covers test types and tools without idempotency or contract testing
  4. Netguru: API Testing Tools — Reviewed as a baseline; tool-focused overview

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.