API and Contract Testing Questions
Testing services and their interfaces directly. Covers REST and other API testing, request/response and schema validation, status and error handling, and contract testing between producers and consumers. Includes service-level and integration testing without a UI.
A service you depend on keeps shipping changes that break your integration with it, and the breakage is only caught after it reaches production. Propose both a technical and a process fix: what would you put in place so a breaking change is caught before it ships, who should own the tests that catch it, and how would you pilot the change and show it actually reduced regressions?
Sample Answer
Direct answer
The fix has to work on two tracks at once: a technical track that catches a breaking change before it ships, and a process track that makes catching it everyone's default rather than something only found in a postmortem. Neither alone is durable, technical checks without ownership get bypassed under deadline pressure, and process without automation depends on someone remembering to look.
Structured elaboration
Technical track. Add consumer-driven contract tests to the dependency relationship: the depending service's real expectations get encoded as a contract, and the upstream service's CI verifies against it before every deploy. This is what actually blocks a breaking change from shipping, rather than catching it after the fact in a bug report. Where a contract test isn't practical to set up quickly, an automated compatibility check that diffs the API's schema or response shape between versions is a cheaper first step that still catches the most common failure mode: a field silently removed, renamed, or retyped.
CI policy. The upstream service's pipeline should fail the build, not just warn, when provider verification against a downstream consumer's contract fails. Placement matters: this check belongs in the upstream service's own CI, where the change originates, not bolted onto the downstream service's pipeline as an afterthought.
Process track. Even a working technical check needs an owner. A PR template or review checklist item that asks "does this change anything a documented consumer depends on" catches the cases contract tests haven't been written for yet. Clear ownership, who's accountable when a contract test fails, and who's accountable for keeping the downstream service's contract accurate as its own needs evolve, is what prevents the check from silently rotting once nobody's paying attention to it.
Retrofitting onto an org with no prior governance. When there's no existing discipline at all, start with a migration plan rather than a mandate: pick the highest-incident-risk dependency pairs first (the ones that have actually caused regressions), prove contract testing catches something real there, and use that as the case for expanding rather than rolling it out everywhere simultaneously with no working example.
Piloting and measuring. Run the new discipline on one or two service pairs first. Track something concrete before and after: the number of contract-related production incidents on those pairs, or the number of contract-test failures caught in CI versus caught in production. That comparison is what actually demonstrates the pilot worked, rather than assuming it did because the process feels more rigorous.
Trade-offs and pitfalls
The most common way this fails is treating it as a one-time cleanup instead of an ongoing discipline: teams write contract tests once, the regressions stop for a while, and the checklist item quietly gets skipped under the next deadline because nothing enforces it anymore. Ownership needs to be durable, not a one-time assignment, and the CI gate needs to actually block a deploy, not just post a warning that's easy to ignore.
Your API tests run against multiple environments, dev, staging, and something closer to production-like. How would you manage the test data across them: how you seed it, keep tests isolated from each other, clean up afterward, and safely reuse anything derived from real production data?
Sample Answer
Direct answer
Managing test data across dev, staging, and prod-like environments comes down to keeping each environment's data isolated from the others while still letting tests reuse setup work safely, and being explicit and careful about which environments are allowed to use anything derived from real production data at all.
Structured elaboration
Seeding. Each environment needs its own seeding strategy appropriate to its purpose: dev environments usually want a small, fast-to-generate dataset covering the common cases a developer needs locally; a prod-like environment used for realistic testing (load testing, a final pre-release check) wants something closer in scale and shape to actual production data: value distributions that resemble production rather than uniform toy values, and referential integrity preserved across related records (a generated order references a generated user that actually exists in the same dataset, and so on), whether that data is purely synthetic or derived from a masked production sample.
Isolation between tests. Within any one environment, tests running concurrently (or in sequence without cleanup) can interfere with each other if they share mutable state, a namespace or prefix per test run (test-run-specific IDs, or a dedicated schema/database per CI job) keeps one test's data from colliding with another's, which matters more as parallelization increases.
Cleanup. Test-created data should be removed after the test that created it, ideally, but a cleanup strategy also needs to handle the case where a test crashes or times out before its own teardown runs, a scheduled sweep that removes anything older than some threshold and matching a test-data naming convention is a reasonable backstop against that kind of leak, so a flaky test failure doesn't also leave permanent garbage in a shared environment.
Reusing data safely across runs. For expensive-to-create fixtures (a large seeded dataset that takes real time to generate), reusing it across multiple test runs rather than regenerating it every time is a real efficiency win, but only if tests that reuse it don't mutate it in ways that would affect a different test relying on the same fixture. Read-only shared fixtures, versus per-test-created and torn-down data for anything a test needs to mutate, is the practical split that keeps this safe.
Production-like data usage and legal considerations. If a prod-like environment uses data DERIVED from real production data (rather than purely synthetic), it needs the same masking and anonymization discipline any production-derived test data needs: actively replacing anything that would identify a real person, a real email swapped for a synthetic one that preserves format and uniqueness but carries no real information, for instance, rather than merely truncating or lightly obscuring the original value. Separately, it needs to actually be permitted by your organization's data-handling policy, which environments are allowed to hold anything derived from real user data is a legal and compliance question as much as a technical one, and getting that answer BEFORE building the pipeline avoids finding out after the fact that a "prod-like" environment was never supposed to have this data in it at all.
Trade-offs and pitfalls
The environment most often mishandled is the "prod-like" one, precisely because it's meant to feel real, which creates pressure to just point it at an actual production snapshot for convenience. That convenience is exactly where a masking failure or a compliance violation tends to originate: treat "prod-like" as still requiring the SAME masking and access-control discipline as any other environment holding anything derived from real data, not as an exception because it's "just for testing."
For each of the HTTP methods GET, POST, PUT, PATCH, and DELETE: is it safe, is it idempotent, and what would you actually assert in an automated test to verify it behaves that way (not just that it returns a status code)?
Sample Answer
Direct answer
Safe is safe, idempotent is a stronger, related property: GET is both. POST is neither. PUT and DELETE are idempotent but not safe (they change state, but repeating them has the same effect as doing it once). PATCH is neither by the HTTP spec, though a specific PATCH endpoint can be designed to behave idempotently.
Structured elaboration
Safe means the method doesn't change server state at all: GET /orders/42 should never modify anything just by being called, whether it's called once or a hundred times.
Idempotent means calling it multiple times has the same effect as calling it once, even if it does change state. PUT /orders/42 with a full representation is idempotent: sending the same PUT twice leaves the resource in the same state as sending it once, because you're replacing the whole thing with the same value each time. DELETE /orders/42 is idempotent too, the resource is gone after the first call, and calling delete again on an already-deleted resource should still leave it gone (typically returning 404 on the repeat, but the end state, "resource doesn't exist," is unchanged).
POST is neither. POST /orders typically creates a new resource each time it's called, so calling it twice with the same body usually creates two orders, not one. That's exactly why idempotency keys exist as a pattern layered on top of POST: a client-supplied unique key that lets the server recognize "this is the same logical request retried" and return the original result instead of creating a duplicate.
PATCH is genuinely ambiguous. A PATCH that sets a field to an absolute value ("set status to shipped") is idempotent in practice. A PATCH that expresses a relative change ("increment quantity by 1") is not: applying it twice doesn't produce the same result as applying it once. The HTTP spec doesn't guarantee either way, so this has to be verified against the specific endpoint's actual semantics, not assumed from the method name alone.
Worked example
For each method, here's what an automated test actually needs to assert, not just that a status code came back, but that the method's guarantee held:
| Method | Safe | Idempotent | Example endpoint | What the test asserts |
|---|---|---|---|---|
| GET | yes | yes | GET /orders/42 | State (e.g. an order-view counter, if one exists) is unchanged after the call; calling it 3 times returns the same body each time. |
| POST | no | no | POST /orders | Two identical calls create two distinct resources (two different IDs), unless an idempotency key is supplied, in which case a repeated call with the same key returns the original resource, not a new one. |
| PUT | no | yes | PUT /orders/42 | Calling it twice with the same body leaves the resource identical to calling it once; a third call still produces the same end state. |
| PATCH | no | depends | PATCH /orders/42 (absolute field set) | Calling it twice produces the same end state as once, for a PATCH designed to be idempotent; explicitly test this rather than assume it. |
| DELETE | no | yes | DELETE /orders/42 | First call removes the resource; a second call on the already-deleted resource still leaves it deleted (whatever status code it returns for the repeat). |
Trade-offs and pitfalls
The most common testing gap here isn't misunderstanding the definitions, it's only testing the single-call happy path and never actually calling an endpoint twice to verify the idempotency claim holds. A PUT that's "idempotent" by the spec but has a subtle bug (say, it appends to an array instead of replacing it) will pass a single-call test and silently fail a repeat-call test, exactly the kind of bug this distinction exists to catch.
An API supports returning either JSON or XML depending on content negotiation. How would you design automated tests that verify the API correctly honors the Content-Type and Accept headers, validates each format against its own schema, and handles an invalid or conflicting header combination?
Sample Answer
Direct answer
Content negotiation testing needs to verify three things: the server honors the Accept header by returning the format the client asked for, it correctly interprets the Content-Type header on requests that include a body, and it fails predictably, not with a confusing error, when the client and server can't agree on a format at all.
Structured elaboration
Honoring Accept. Send the same logical request with Accept: application/json and Accept: application/xml, and confirm the response's Content-Type header and body format actually match what was requested, not just that both return 200. A response that ignores Accept and always returns JSON regardless is a real, common bug this specifically catches.
Interpreting Content-Type on requests. For an endpoint accepting a body (a POST or PUT), send a valid JSON body with Content-Type: application/json and a valid XML body with Content-Type: application/xml, confirming each is parsed correctly. Also send a body whose actual content doesn't match its declared Content-Type (JSON content labeled as XML, for instance) and confirm the server rejects it rather than attempting to guess the real format.
Schema validation per format. JSON responses get validated against a JSON Schema; XML responses get validated against an XSD (XML Schema Definition). These are enforcing the same underlying contract, but validated with format-appropriate tools, since a JSON Schema validator can't meaningfully check XML structure and vice versa.
Invalid or conflicting combinations. An Accept header requesting a format the API doesn't support at all (Accept: application/pdf) should return 406 Not Acceptable, not silently fall back to a default format and not error unpredictably. A request body whose Content-Type the API doesn't support should return 415 Unsupported Media Type.
Parsing correctness beyond the format itself. Once the format is settled, still verify field-level correctness within that format: a JSON response's fields have correct types, an XML response's elements and attributes match the expected schema, since format negotiation succeeding doesn't guarantee the CONTENT within that format is correct.
Worked example (assertion sequence)
1. GET /users/1 Accept: application/json
-> 200, Content-Type: application/json, body validates against user.schema.json
2. GET /users/1 Accept: application/xml
-> 200, Content-Type: application/xml, body validates against user.xsd
3. GET /users/1 Accept: application/pdf
-> 406 Not Acceptable
4. POST /users Content-Type: application/json, body: valid JSON
-> 201, resource created
5. POST /users Content-Type: application/xml, body: valid JSON text (mismatched)
-> 400 or 415, request rejected as malformed for its declared type
Trade-offs and pitfalls
A subtlety worth testing explicitly: an Accept header can list multiple acceptable formats with quality values (Accept: application/xml;q=0.9, application/json;q=1.0), and a compliant server should honor the preference order, not just pick whichever format it implemented first. If an API only ever supports one format in practice, testing multi-format negotiation at all may be unnecessary complexity, worth confirming the API actually needs to support more than one format before building out this whole test surface for it.
An API supports multiple versions simultaneously, selected by a request header, and each version has its own response schema (with some fields deprecated in newer versions). Design a test harness that picks the right schema to validate against based on that version header, and explain how it stays maintainable as new versions ship.
Sample Answer
Direct answer
Selecting a schema per API version means the harness can't hardcode which schema file it uses. It needs to read the version from the request (typically a header like Api-Version), look up the matching schema, and know how to gracefully skip or relax checks for fields that are deprecated in that version rather than failing on them.
Structured elaboration
Harness structure. Three pieces do the work: a schema registry (a simple mapping from version string to schema object, loaded once at startup from a directory of schema files, one per version), a version resolver that reads the version out of the actual response being validated (from the request header that was sent, or from a version field the API itself echoes back), and a validation step that looks up the right schema and runs it, same as in a single-version harness.
Handling deprecated fields. A field being deprecated in a newer version, but still present for backward compatibility, is exactly the kind of change JSON Schema's additionalProperties and per-field constraints are meant to express, mark a deprecated field as still allowed but no longer required, so its presence or absence in the response doesn't fail validation either way.
Skipping or adapting. For a version whose schema genuinely doesn't have an equivalent field at all (not deprecated, just never existed), the harness needs an explicit "skip this check for this version" mechanism rather than silently treating a missing schema entry as a validation error, otherwise every new version addition risks breaking the harness itself, not just the tests it's meant to run.
Worked example (illustrative outline)
schema_registry = {
"v1": load_schema("schemas/user_v1.json"),
"v2": load_schema("schemas/user_v2.json"), # phone_number now optional/deprecated
}
def validate_versioned_response(response, schema_registry):
version = response.headers.get("Api-Version", "v1")
schema = schema_registry.get(version)
if schema is None:
raise ConfigError(f"no schema registered for version {version}")
return jsonschema_validate(response.json(), schema)
A v2 schema for a field like phone_number that used to be required would set it to optional rather than removing it from the schema entirely, so a v1-shaped response validated against v2 still passes (the field is present, just no longer required) and the harness doesn't need version-specific branching logic beyond picking the right schema.
CI configuration. The registry of schema files is the thing that needs updating when a new API version ships, not the harness code itself, which keeps the maintenance burden on the (smaller, more frequent) task of adding a schema file rather than the (larger, riskier) task of touching harness logic. A CI check that fails if a version appears in traffic or in test fixtures but has no corresponding registered schema catches the harness silently falling back to the wrong version's rules.
Trade-offs and pitfalls
The harness's own correctness depends on the version-resolution step matching reality: if the API's actual versioning scheme is inconsistent (some endpoints version by header, others by URL path), a harness built assuming one scheme will silently validate against the wrong schema rather than failing loudly, worth explicitly testing the resolver itself against a handful of known request/response pairs, not just trusting it once it's wired up.
Unlock Full Question Bank
Get access to all 47 API and Contract Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.