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.
What does a solid test-data strategy for API and service tests actually look like in practice? Cover how you'd decide between generating data on the fly versus using fixed fixtures, when synthetic data is good enough versus when you need something closer to real production data, and how you keep tests from interfering with each other's data.
Sample Answer
Direct answer
A solid test-data strategy for API and service tests rests on four decisions made deliberately rather than by default: generate-on-the-fly versus fixed fixtures, synthetic versus production-derived data, how tests stay isolated from each other's data, and what actually needs cleanup versus what can be safely shared.
Structured elaboration
Generated on the fly vs. fixed fixtures. A fixture generated fresh for each test (a new user created at the start of the test, torn down at the end) gives strong isolation, no test can be affected by another test's leftover state, at the cost of some setup time per test. A fixed, shared fixture (a small set of known reference records seeded once) is faster to use repeatedly but risks one test's assumptions about that shared data becoming invalid if another test modifies it. The practical split: generate fresh data for anything a test needs to MUTATE, and use shared fixtures only for read-only reference data nothing is expected to change.
Synthetic vs. closer-to-production data. Purely synthetic data (templated names, generated emails) is simplest and carries no privacy risk, but can miss bugs that only show up with realistic value distributions or realistic correlations between fields. Production-derived data (masked or anonymized) is more realistic but requires real discipline around what's actually safe to use in a test environment, and is usually reserved for a smaller number of higher-fidelity tests (load testing, a final pre-release check) rather than the bulk of the day-to-day suite, where synthetic data's speed and simplicity matter more than its lower realism.
Isolation between tests. However the data is generated, tests running concurrently need to not collide: namespacing (a unique prefix or identifier per test run), using ephemeral per-test-run resources (a fresh database schema, a dedicated test namespace), or simply ensuring every generated record's identifiers are unique enough that two tests' data can coexist without either noticing the other.
Cleanup. Data a test creates should be removed when the test finishes, via the test's own teardown when things go well, and via a backstop (a scheduled sweep for anything matching a test-data naming pattern and older than some threshold) for the cases where a test crashes before its own teardown runs. Shared, read-only reference data doesn't need this kind of cleanup at all, that's part of why the mutate-vs-read-only split above matters: it determines which data even needs a cleanup story.
Trade-offs and pitfalls
The mistake that causes the most downstream pain is treating "test data strategy" as one uniform decision applied to everything, generate everything fresh, or share everything, rather than recognizing that different data has different needs. A shared reference fixture that's occasionally, accidentally mutated by a test that was supposed to only read it is one of the more confusing categories of flaky test to debug, since the failure shows up in a DIFFERENT, unrelated test that happened to run afterward and inherited the corrupted shared state, not in the test that actually caused the problem.
You're asserting that an API uses HTTP status codes correctly across the full 1xx-5xx range. How would you organize those assertions by range, and what's a realistic way a service could return the wrong status code while still looking superficially correct? Write a test that would catch that specific case. How should an automated test treat an asynchronous 202 response differently from an immediate 200 or 201?
Sample Answer
Direct answer
Organize the assertions by range first (1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error), then within each range assert the SPECIFIC code, not just the range, since two codes in the same range can mean very different things to a caller (200 vs 201, 401 vs 403).
Structured elaboration
Why range alone isn't enough. A test that only checks "is this a 2xx" would pass whether the API returned 200 or 201, but those mean different things: 200 says "here's the current state of something that already existed," 201 says "I just created something new for you," and a client deciding whether to expect a Location header, for instance, cares about that difference. The same logic applies to 401 (you're not authenticated at all) vs 403 (you're authenticated, but not allowed to do this): a client's retry-after-login logic depends on knowing which one it got.
A realistic way this goes wrong. A service can return HTTP 200 while its JSON body describes a failure, {"status": "error", "message": "insufficient funds"} with a 200 status code, because someone wired up a generic success wrapper without threading the actual outcome through to the status code. A test built to catch this doesn't just check status_code == 200; it also inspects the body for that error-shaped structure and asserts the two are consistent: a 200 with an error-shaped body is itself the bug being tested for.
Synchronous vs. asynchronous responses. A 200 or 201 means the requested work is already done and the body reflects the final result. A 202 Accepted means the request was valid and queued, but the work isn't done yet, so a test against a 202 response can't assert on a final-state body the way it would for 200/201; instead it needs to assert the response includes a way to check status later (a status URL, a job ID) and then poll that separately to confirm eventual completion.
Worked example
def test_status_code_and_body_consistency(response):
assert response.status_code in (200, 201, 202), f"unexpected success code: {response.status_code}"
body = response.json()
looks_like_an_error = isinstance(body, dict) and body.get("status") == "error"
assert not looks_like_an_error, (
f"got HTTP {response.status_code} but response body describes a failure: {body}"
)
if response.status_code == 202:
assert "status_url" in body or "job_id" in body, (
"202 Accepted response has no way for the caller to check completion status"
)
Executed against three fixture responses, an honest 200 with a matching body, a 200 wrongly wrapping an error, and a 202 missing a status URL:
class FakeResp:
def __init__(self, status_code, body):
self.status_code = status_code
self._body = body
def json(self):
return self._body
good = FakeResp(200, {"id": 1, "name": "Ada"})
bad_wrapper = FakeResp(200, {"status": "error", "message": "insufficient funds"})
bad_async = FakeResp(202, {"id": 1})
test_status_code_and_body_consistency(good) # passes
try:
test_status_code_and_body_consistency(bad_wrapper)
except AssertionError as e:
print("caught:", e)
try:
test_status_code_and_body_consistency(bad_async)
except AssertionError as e:
print("caught:", e)
Output:
caught: got HTTP 200 but response body describes a failure: {'status': 'error', 'message': 'insufficient funds'}
caught: 202 Accepted response has no way for the caller to check completion status
Trade-offs and pitfalls
A common mistake in the other direction is being too strict about which specific error code within 4xx a client should expect, some APIs legitimately return 400 for a validation error that another team's convention would call 422, and asserting the exact code without also asserting the response body actually describes the specific problem can make tests brittle to a harmless convention choice rather than catching a real bug.
Write a parameterized test that checks an API's input validation by sending it several different invalid payloads and confirming each one produces the expected status code and error message. How would you structure the test data so the suite stays maintainable as more invalid cases are added?
Sample Answer
Direct answer
Below is a parameterized pytest test that sends several distinct invalid payloads to an API and confirms each one produces the expected status code and error message, with the test data pulled out into a structured, named table rather than hardcoded per test case.
Structured elaboration
Externalizing the test data (a list of named cases, each with its own invalid payload and expected outcome) keeps the test readable as data grows: adding a new invalid-input case is a one-line addition to the table, not a new copy-pasted test function.
Worked example
import pytest
import requests
BASE_URL = "http://localhost:5000"
INVALID_PAYLOAD_CASES = [
pytest.param(
{"email": "not-an-email", "password": "secret123", "age": 30},
400, "invalid email format",
id="malformed_email",
),
pytest.param(
{"email": "ada@example.com", "password": "", "age": 30},
400, "password is required",
id="empty_password",
),
pytest.param(
{"email": "ada@example.com", "password": "secret123", "age": -5},
400, "age must be a positive integer",
id="negative_age",
),
pytest.param(
{"email": "ada@example.com", "password": "secret123"},
400, "age is required",
id="missing_age",
),
pytest.param(
{"email": "ada@example.com", "password": "secret123", "age": "thirty"},
400, "age must be a positive integer",
id="age_wrong_type",
),
]
@pytest.mark.parametrize("payload,expected_status,expected_error_substring", INVALID_PAYLOAD_CASES)
def test_input_validation_rejects_invalid_payloads(payload, expected_status, expected_error_substring):
resp = requests.post(f"{BASE_URL}/users", json=payload)
assert resp.status_code == expected_status, (
f"case with payload {payload}: expected {expected_status}, got {resp.status_code}"
)
body = resp.json()
assert expected_error_substring in body.get("error", "").lower(), (
f"case with payload {payload}: expected error containing "
f"'{expected_error_substring}', got '{body.get('error')}'"
)
Executed against a local Flask fixture implementing matching validation logic:
test_input_validation_rejects_invalid_payloads[malformed_email] PASSED
test_input_validation_rejects_invalid_payloads[empty_password] PASSED
test_input_validation_rejects_invalid_payloads[negative_age] PASSED
test_input_validation_rejects_invalid_payloads[missing_age] PASSED
test_input_validation_rejects_invalid_payloads[age_wrong_type] PASSED
5 passed in 0.09s
Why pytest.param(..., id=...) matters here. Naming each case explicitly (malformed_email, negative_age, and so on) is what makes a CI failure report actionable: test_input_validation_rejects_invalid_payloads[negative_age] FAILED tells you immediately which specific invalid input broke, versus an unnamed parametrize that would report only a numeric index.
Trade-offs and pitfalls
Asserting on an error message SUBSTRING rather than the full exact string is a deliberate choice: it lets the server's exact wording evolve (a copy change, a rephrased message) without breaking every test, while still confirming the error is actually ABOUT the right thing, catching a case where the server returns a generic "validation failed" for every input regardless of which field was actually wrong, which a substring check on the specific expected phrase would catch and a bare resp.status_code == 400 check would miss entirely.
You consume webhooks from an external vendor that signs each payload with HMAC SHA-256 and includes a timestamp to guard against replay. Write a Postman pre-request script (or describe the equivalent code) that generates the correct signature header for a test webhook request, and describe the automated tests you'd write on the receiver side to verify signature validation, timestamp freshness, and replay protection.
Sample Answer
Direct answer
Generating the signature is a few lines: HMAC (hash-based message authentication code) SHA-256 over the timestamp and raw body, using the shared secret. Verifying it correctly on the receiver side is the part that actually matters, and it has three genuinely separate checks: the signature is valid, the timestamp is fresh, and this exact request hasn't been processed before.
Structured elaboration
Signing (sender side, what the Postman pre-request script does). The vendor's convention here is standard: concatenate the timestamp and the raw request body with a separator, then HMAC-SHA256 that combined string with the shared secret, and send the result as a header alongside the timestamp itself. The receiver has to sign the exact same bytes the same way to check it, so the pre-request script and the receiver's verification logic must agree on the signed-content format down to the separator character.
Verifying (receiver side), three checks, each catching a different failure:
- Timestamp freshness. Reject anything outside a tolerance window (a few minutes is typical) before doing anything else. This is what limits how long a captured request stays replayable even before the replay check runs, and it's cheap to check first so an obviously stale request doesn't cost a cryptographic comparison.
- Signature validation. Recompute the expected signature from the secret, the timestamp, and the body, and compare it to the header using a constant-time comparison, never a plain string equality, which can leak timing information about how many leading bytes matched and make the secret guessable byte by byte over many attempts.
- Replay protection. Even a validly-signed, fresh request should only be accepted once. Track signatures (or a vendor-supplied event ID, if one exists) already processed, and reject a repeat.
Worked example
The pre-request script that generates the signature, using CryptoJS, the crypto library Postman's sandbox exposes as a global:
const secret = 'test-webhook-secret-shared-with-vendor';
const timestamp = Math.floor(Date.now() / 1000).toString();
const body = pm.request.body.raw;
const signedContent = timestamp + '.' + body;
const signature = CryptoJS.HmacSHA256(signedContent, secret).toString(CryptoJS.enc.Hex);
pm.request.headers.upsert({ key: 'X-Webhook-Timestamp', value: timestamp });
pm.request.headers.upsert({ key: 'X-Webhook-Signature', value: signature });
And the receiver-side verification, in Python:
import hmac, hashlib, time
def verify_webhook(secret, timestamp, body, signature_header, seen_signatures, max_age_seconds=300):
ts = int(timestamp)
if abs(time.time() - ts) > max_age_seconds:
return False, "stale timestamp"
signed_content = timestamp.encode() + b"." + body
expected = hmac.new(secret.encode(), signed_content, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature_header):
return False, "signature mismatch"
if signature_header in seen_signatures:
return False, "replay detected"
seen_signatures.add(signature_header)
return True, "accepted"
Verified end to end with a minimal receiver, not just the isolated function above. Wiring verify_webhook into a small Flask endpoint and driving it with Flask's test client (real HTTP request/response objects, no mocking) confirms the three cases the tests need to cover:
from flask import Flask, request, jsonify
SECRET = "test-webhook-secret-shared-with-vendor"
seen_signatures = set()
app = Flask(__name__)
@app.route("/webhook", methods=["POST"])
def webhook():
timestamp = request.headers.get("X-Webhook-Timestamp", "")
signature = request.headers.get("X-Webhook-Signature", "")
body = request.get_data()
ok, reason = verify_webhook(SECRET, timestamp, body, signature, seen_signatures)
if ok:
return jsonify({"status": reason}), 200
if reason == "replay detected":
return jsonify({"error": reason}), 409
return jsonify({"error": reason}), 400
Driving it with three real round trips through app.test_client():
fresh first-time request -> 200 {'status': 'accepted'}
replayed request -> 409 {'error': 'replay detected'}
stale (1hr old) request -> 400 {'error': 'stale timestamp'}
Exactly the three outcomes the acceptance criteria need: a fresh, correctly-signed request accepted, the identical request replayed and rejected as a duplicate, and a correctly-signed but hour-old request rejected as stale.
Trade-offs and pitfalls
A real gotcha found while building this, worth knowing before you hit it live. The obvious "modernization" of the pre-request script, replacing the bare CryptoJS global with const CryptoJS = require('crypto-js'), actually breaks in the current Postman sandbox: CryptoJS is already bound as a global, and redeclaring it throws SyntaxError: Identifier 'CryptoJS' has already been declared. The bare global form is deprecated (Postman's own console warns about it) but is still the one that actually works today; don't "fix" a deprecation warning by introducing a naming collision that breaks the script outright, verify a replacement actually runs before trusting a deprecation notice's suggested fix.
The signed-content format (timestamp, a separator, then the raw body, in that exact order and byte form) has to match the vendor's real convention exactly; a mismatch anywhere (a different separator, a parsed-and-re-serialized body instead of the raw bytes, a different byte encoding) makes every signature fail to verify even though the logic is otherwise correct, so the first thing to check against a real vendor's docs, not assume, is the exact signed-content construction.
Walk through how a consumer-driven contract testing tool like Pact actually operates end to end: how the consumer test generates a contract, how that contract gets published and versioned, and how the provider verifies against it in its own CI. Where does this approach break down, and how would you introduce it to a team that has never used it before?
Sample Answer
Direct answer
Mechanically, a Pact-style workflow has four moving parts: the consumer writes a test against a local mock of the provider, that test's run produces a contract file, the contract gets published to a broker, and the provider's own CI pulls the latest contracts and verifies its real implementation against each one.
Structured elaboration
1. Consumer side. The consumer team writes a normal-looking test, but instead of hitting a real provider, it hits a mock server that the testing library spins up locally. The test tells the mock "when you get this request, respond with this." The consumer's actual client code makes the call, and the test asserts on what comes back. Because the mock only knows how to answer the interactions the test set up, running the test also produces a JSON file describing exactly those interactions: the contract (Pact calls it a "pact file").
2. Publishing. The consumer's CI pipeline pushes that contract to a broker, tagged with information like which consumer version and branch produced it.
3. Provider verification. The provider's CI pulls every contract published against it (from every consumer) and, for each one, replays the interaction: it sets up whatever state the contract's scenario needs, this is the "provider state," a hook the provider team writes, for example "given a user with ID 42 exists," then makes the request the contract describes against the real provider code and checks the response matches what the contract expects.
4. Versioning and tagging. Every verification result gets recorded against the specific consumer version and provider version involved. That's what lets the broker answer the operational question that actually matters: "if I deploy provider version X, is it currently compatible with whatever consumer versions are live in production?" Tags (like "main" or "production") let this check track what's actually deployed rather than every historical version.
False positives and negatives to watch for: a consumer that asserts on fields it never actually uses will fail verification when the provider changes something harmless, false positive from the contract's point of view even though nothing broke. A consumer that fails to assert on a field it silently depends on will let a real break through unverified. The discipline that keeps this workflow honest is asserting on exactly, and only, what the consumer's code reads.
Trade-offs and pitfalls
Two limitations come up often in practice. First, schema evolution: contracts pin a specific shape, so a provider that legitimately wants to evolve its schema (adding a field, tightening a type) needs an explicit compatibility policy, otherwise every provider change becomes a scramble to get every consumer to update its contract. Second, at real scale, a popular provider can accumulate a large contract surface: dozens of consumers, each with several scenarios, and provider verification time and coordination overhead both grow with that surface. Teams manage this with tagging and "can I deploy" checks (only re-verify against what's actually in production, not every historical contract) and with clear ownership so a provider team isn't blocked waiting on an unresponsive consumer team. Introducing this into an existing frontend/backend relationship usually goes smoother when it starts on one well-understood endpoint pair rather than a big-bang rollout, and when both sides agree up front on who owns writing and maintaining the tests. A contract that's too rigid, asserting more than the consumer needs, is a common early mistake, since it makes contract tests brittle in exactly the way they were meant to avoid, and it tends to happen when a contract is written to describe an entire response shape instead of just the fields actually consumed.
Unlock Full Question Bank
Get access to all 29 API and Contract Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.