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.
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.
Describe what a comprehensive testing approach for a REST API actually covers end to end: functional correctness, schema validation, error handling, authentication, and how contract testing fits alongside all of that. What tools would you reach for, and how does an exploratory pass differ from your automated suite?
Sample Answer
Direct answer
A comprehensive API testing approach layers several distinct concerns on top of each other: functional correctness first, then schema validation, then error handling, then auth, and finally the contract between this service and whoever consumes it, each one catching a different class of bug the others wouldn't.
Structured elaboration
Functional checks. Does each endpoint do what it's supposed to for valid input: correct status codes, correct data in the response, correct side effects (a POST actually creates what it claims to). This is the foundation everything else builds on.
Schema validation. Beyond "does the happy path work," does the response's SHAPE match what's documented or agreed, every time, not just in the cases someone happened to manually check. This catches drift between implementation and documentation that functional testing alone, if it only asserts on a few specific fields, can miss.
Error handling. Deliberately sending invalid, malformed, or edge-case input and confirming the API fails predictably and informatively, the right status code, a clear error message, rather than a generic 500 or, worse, silently accepting bad input and producing corrupted state.
Authentication and token flows. Confirming protected endpoints actually enforce auth (reject missing/invalid/expired credentials) and that the specific token lifecycle, issuance, refresh, expiry, revocation, behaves correctly, not just that a valid token happens to work once.
Rate-limiting behavior. Confirming the API actually throttles once a client exceeds its limit, and that it communicates that throttling clearly (a 429 with retry guidance) rather than degrading in some undocumented way.
Contract testing. Where this service has consumers (other services, or the same service's client SDK), consumer-driven contract tests confirm the service continues to honor what those consumers actually depend on, catching a class of regression, "this change is fine in isolation but breaks a real caller", that testing the service by itself can't see.
Tools. For manual and exploratory work, a tool like Postman is fast to work in interactively. For the durable, CI-enforced regression suite, a code-based framework (REST-Assured for a Java stack, pytest with requests for Python) integrates naturally with the rest of the codebase's testing and CI setup. For contract testing specifically, a dedicated tool like Pact handles the consumer/provider verification workflow that a general-purpose HTTP testing library doesn't natively support.
Exploratory vs. automated. Exploratory testing, poking at an API by hand, trying inputs nobody thought to write a formal test for, is how you DISCOVER what needs testing, especially early on or when integrating with something unfamiliar. The automated suite is where you PRESERVE that discovery so it keeps being checked on every future change; a bug found exploratorily that never gets turned into an automated test only protects you once.
Trade-offs and pitfalls
Treating this as one flat checklist to complete once, rather than as several genuinely different KINDS of testing each with their own cadence and depth, undersells how differently these axes need to be maintained: schema validation and functional tests belong on every CI run, contract tests need active coordination with real consumers to stay meaningful, and exploratory testing is an ongoing practice, not a phase you finish. Comprehensive doesn't mean "one big suite that does everything the same way," it means each of these concerns getting the specific kind of attention it actually needs.
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.
Your team has an SLA that a given API endpoint should respond within a set time for the large majority of requests. How would you write an automated test that checks this without it becoming flaky in CI? Think about what tolerance you'd allow and whether a violation should fail the build outright or just raise a warning.
Sample Answer
Direct answer
Asserting a response-time SLA without making the test flaky means testing against a statistical tolerance, not a single hard cutoff on a single request, and treating the result as a warning until you have enough samples to trust it as a real signal.
Structured elaboration
Why a single-request threshold is flaky. A single request's response time is noisy: network jitter, a GC pause, a neighboring process briefly using CPU on the CI runner, any of these can push one request over a hard threshold without the service actually being slow in any way that matters. Asserting response_time < 500ms on one request will occasionally fail for reasons that have nothing to do with the SLA actually being violated.
Percentile-based assertions instead. The SLA itself is usually stated as a percentile ("95% of requests under 500ms"), so the test should match that shape: send a batch of requests (enough to make a percentile calculation meaningful, tens rather than one or two), compute the actual p95 from that batch, and assert the p95 is under the threshold, tolerating individual outliers the way the SLA itself does.
Tolerance windows. Even a percentile calculated from a modest batch size has some natural variance run to run. Building in an explicit tolerance (asserting p95 under 550ms rather than exactly 500ms, for a documented 500ms SLA) absorbs that natural variance without either being so loose it never catches a real regression or so tight it fails on noise.
Fail vs. warn. A reasonable policy: a violation of the tolerance-adjusted threshold on a single CI run raises a warning, visible but non-blocking, while a violation that's CONSISTENT across several runs (say, 3 consecutive CI runs, or a sustained trend visible over a day) escalates to actually failing the build. This distinguishes a one-off noisy run from a genuine regression without requiring a human to manually triage every borderline case.
Minimizing noise in how the test runs. Running the timing batch against a dedicated, unshared instance of the service (rather than a busy shared staging environment where other tests' load bleeds into your timing measurements) removes one major source of noise, and running the batch as a tight, back-to-back burst rather than spread across a longer window reduces exposure to any transient environmental blip.
Worked example
import statistics
def assert_p95_under_sla(response_times_ms: list[float], sla_ms: float, tolerance_pct: float = 0.10):
# n=100 splits the data into 99 cut points, one for each percentile from 1 to 99.
# Index 94 (0-based) is the 95th of those 99 cut points, i.e. the 95th percentile.
p95 = statistics.quantiles(response_times_ms, n=100)[94]
threshold = sla_ms * (1 + tolerance_pct)
assert p95 <= threshold, f"p95={p95:.1f}ms exceeds tolerance-adjusted threshold={threshold:.1f}ms (SLA={sla_ms}ms)"
return p95
samples_ok = [420, 430, 410, 405, 440, 415, 425, 460, 480, 400] * 10 # p95 well under 550ms
p95 = assert_p95_under_sla(samples_ok, sla_ms=500)
print(f"passed, p95={p95:.1f}ms")
Output:
passed, p95=480.0ms
Trade-offs and pitfalls
A percentile-based assertion needs enough samples to be statistically meaningful; asserting a p95 from a batch of 5 requests isn't really measuring the 95th percentile at all (there's no clean way to compute a meaningful p95 from 5 points), it's an unreliable dressed-up version of the same single-outlier flakiness this approach is meant to fix. Enforcing a minimum sample size (tens of requests at least) is part of the design, not an optional nicety.
Unlock Full Question Bank
Get access to all 44 API and Contract Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.