API Testing Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Why move API checks from Postman into code-based tests over time?
Correct answer: Code lives in Git with review, reuse and normal CI tooling
Tests in the same repo as the service are reviewed with the code, share helpers and run like any test suite. Postman stays useful for exploration.
2. What does SuperTest let you do in a Node.js project?
await request(app) .post("/api/users") .send({ name: "Ann" }) .expect(201);Correct answer: Call an Express-style app's endpoints in tests and assert responses
SuperTest can start the app in memory, so tests don't need a running server or a free port.
3. What is REST Assured?
Correct answer: A Java library for writing readable API tests
It offers a given/when/then style:
given().body(...).when().post("/users").then().statusCode(201).4. How do you validate a response body against a JSON Schema in JavaScript tests?
Correct answer: Compile the schema with a validator like Ajv and check the body
Ajv returns validation errors with paths like
/items/0/price, which makes failures easy to read.5. What does
additionalProperties: falsein a response schema catch?Correct answer: Unexpected fields, such as leaked internal data
Strict schemas detect new or leaked fields like
passwordHash. Teams decide per API whether strictness helps or causes noise.6. What is consumer-driven contract testing?
Correct answer: Consumers record expectations that the provider verifies in its pipeline
With Pact, the frontend's tests create a contract file. The backend's CI replays it to prove it still meets those expectations.
7. What can contract tests catch that unit tests on each side can't?
Correct answer: A provider change that breaks what a consumer relies on
Each side may pass its own tests while disagreeing on a field name or type. The contract makes the shared assumption explicit.
8. When is an OpenAPI-based contract check a good alternative to Pact?
Correct answer: When there are many unknown consumers, e.g. a public API
Validating real responses against the published spec, or running tools that test the spec, catches drift without consumer-written contracts.
9. What does WireMock provide?
Correct answer: A configurable HTTP stub server for dependencies
You define which requests return which responses, including delays and errors, so tests don't need the real third-party service.
10. Why simulate a slow dependency in an API test?
Correct answer: To check timeouts, retries and error messages
A stub with a 10-second delay shows whether the service fails fast with a clear error or hangs until the client gives up.
11. What is the difference between
502,503and504?Correct answer: Bad upstream response, service unavailable, upstream timeout
These codes help locate a problem: a gateway got garbage, the service is down or overloaded, or the gateway waited too long.
12. An endpoint returns
202 Accepted. How should a test continue?Correct answer: Poll the status endpoint until the job finishes, with a timeout
202 means the work was accepted for later processing. The test checks the final state via a status URL or event.
13. What is an idempotency key for a POST request?
Correct answer: A unique key so a retried request isn't processed twice
Payment APIs accept a key in a header. Sending the same key again returns the first result instead of charging twice.
14. How do you test that an API handles a double-click on "Pay" safely?
Correct answer: Send two identical requests at once and check one charge
Parallel requests reveal race conditions that sequential tests miss: duplicate orders, double charges, wrong counters.
15. What does
If-Matchwith an ETag protect against?Correct answer: Overwriting changes someone else made in between
If the resource changed since the client read it, the server answers
412 Precondition Failedinstead of silently losing an update.16. What should a request with
If-None-Matchand a matching ETag return?Correct answer:
304 Not Modifiedwith no bodyThis saves bandwidth. Tests check the ETag changes when the resource changes and stays the same otherwise.
17. Why check
Cache-Controlheaders on API responses?Correct answer: Wrong caching can show stale or private data to others
A
publiccache on/mecould serve one user's profile to another through a CDN. Private data needsprivateorno-store.18. How do you test a rate limit of 100 requests per minute?
Correct answer: Send 101 requests and check the 101st gets 429 with Retry-After
Also check that the limit resets, counts per user or key as documented, and can't be bypassed by changing headers.
19. What is a known problem of offset pagination like
?page=3?Correct answer: Items shift when data changes, causing gaps or duplicates
If an item is added while a client pages through, the next page repeats one. Cursor pagination avoids this.
20. What should you test for cursor-based pagination?
Correct answer: Following cursors returns all items once, and bad cursors give 400
Check the last page has no next cursor, tampered cursors are rejected, and the order stays stable.
21. What is mass assignment in an API?
Correct answer: The API saves fields the client shouldn't set, like
roleSending
{"name":"Ann","role":"admin"}to a profile update shouldn't make you an admin. Testers try extra privileged fields.22. What is broken function level authorization?
Correct answer: A normal user can call admin-only endpoints
Hiding admin buttons doesn't protect
/admin/users. Testers call such endpoints with low-privilege tokens.23. How do you systematically test object-level authorization?
Correct answer: Create data as user A and try every operation on it as user B
Read, update, delete and nested resources should all deny user B. Unguessable IDs help but don't replace checks.
24. Which test input checks for SQL injection in a search parameter?
Correct answer:
' OR 1=1 --and checking results and errorsIf the response changes oddly or shows a database error, input may reach SQL unescaped. Parameterized queries prevent it.
25. What should an error response for invalid input look like?
Correct answer: A consistent format with a code, message and the problem fields
Formats like RFC 9457 problem details make errors predictable for clients and easy to assert in tests.
26. Why is a database error message in an API response a security finding?
Correct answer: It reveals internals that help attackers
Table names, SQL and stack traces should go to logs, not clients. The client gets a generic message and a correlation ID.
27. Why do correlation or request IDs help API testing?
Correct answer: They link a failing response to the exact server logs
Including the ID from a response header in a bug report lets developers find the trace in seconds.
28. In the OAuth 2.0 client credentials flow, who gets the token?
Correct answer: An application acting on its own behalf
Service-to-service calls use client ID and secret to get a token. There's no user, so user-level scopes don't apply.
29. What should you test about refresh tokens?
Correct answer: They issue new access tokens, expire, and stop working when revoked
Also check rotation (old refresh token rejected after use) and logout revoking them.
30. Which JWT checks should an API tester try?
Correct answer: Tampered payload, wrong signature, expired
exp,alg: noneA JWT payload is only Base64-encoded. The server must verify the signature and claims; tampered tokens must give 401.
31. Why can a JWT be decoded by anyone who has it?
Correct answer: Its payload is Base64url-encoded, not encrypted
So tokens must not contain secrets or personal data beyond what's needed. The signature only protects against changes.
32. How do you test file upload with
multipart/form-data?Correct answer: Valid files, wrong types, too-large files and renamed extensions
Check limits (
413 Payload Too Large), content-type validation (not just extension), malicious names and storage.33. What does
413 Content Too Largemean?Correct answer: The request body exceeds the server's limit
Testers check the limit is enforced before the server processes the whole body, protecting it from huge uploads.
34. Which change to a JSON response is usually backward compatible?
Correct answer: Adding a new optional field
Well-written clients ignore unknown fields. Removing, renaming or retyping fields breaks them.
35. How should a tester check an API deprecation?
Correct answer: Old version works, sends deprecation headers, docs give an end date
Headers like
DeprecationandSunsetwarn clients. Both versions need tests until the old one is retired.36. What is data-driven testing in API tests?
Correct answer: Running the same test with many input rows from a file or table
Postman and Newman can read CSV or JSON files; code-based tests use parameterized cases. Each row checks one input and expected result.
37. Why are monetary amounts often sent as strings or integers of cents?
Correct answer: Floating-point numbers can't represent many decimals exactly
0.1 + 0.2isn't exactly0.3in floating point. Testers check rounding, currency and totals.38. What should a test check about time zones in an API?
Correct answer: Timestamps include an offset or use UTC consistently
A date shown a day off for some users is a classic bug. ISO 8601 with
Zor an offset removes ambiguity.39. How do you make API tests independent of each other?
Correct answer: Each test creates its own data and cleans up afterwards
Independent tests can run in parallel and in any order, and a failure doesn't cascade.
40. What is a common cause of flaky API tests?
Correct answer: Shared test data and asynchronous processing
Waiting for eventual results with polling, isolating data and controlling time fix most flakiness.
41. What does a test of webhook delivery need to check?
Correct answer: Payload, signature, retries on failure and duplicate handling
Providers retry failed deliveries, so receivers must verify signatures and handle duplicates and out-of-order events.
42. Why verify a webhook signature?
Correct answer: To make sure the request really comes from the provider
Anyone can send a POST to your URL. An HMAC signature with a shared secret proves origin and integrity.
43. What is GraphQL query depth or complexity limiting for?
Correct answer: Preventing expensive nested queries from overloading the server
A deeply nested query like friends of friends of friends can explode. Tests check such queries are rejected.
44. Why might GraphQL introspection be disabled in production?
Correct answer: It shows the full schema, helping attackers explore
Introspection is useful in development. Testers check the production setting matches the team's security policy.
45. What is the N+1 problem in an API?
Correct answer: One request triggers a query per item, making it slow
A list of 100 orders with 100 extra queries for customers is slow. Testers notice it by response time growing with list size.
46. What is special about testing a gRPC API?
Correct answer: It uses Protobuf over HTTP/2 and needs gRPC tools
Tools like grpcurl or Postman's gRPC support send requests using the
.protodefinition. Status codes differ from HTTP ones.47. How should API tests handle environment-specific values?
Correct answer: Config or env variables for base URLs, keys and accounts
The same suite then runs on local, staging and preview environments, with secrets kept out of the code.
48. Why add security header checks to API tests?
Correct answer: Missing headers like HSTS or
nosniffweaken protectionSimple checks for
Strict-Transport-Security,X-Content-Type-Optionsand CORS settings catch configuration regressions.49. How do you test CORS configuration of an API?
Correct answer: Send different
Originheaders and check the allow headersAllowed origins should get
Access-Control-Allow-Origin; others shouldn't.*together with credentials is a misconfiguration.50. What does Postman's
pm.response.to.have.jsonSchema(schema)do?Correct answer: Validates the response body against a JSON Schema
It turns a structure check into one assertion. Keep schemas in shared variables or files to reuse them.
51. What are Postman dynamic variables like
{{$guid}}useful for?Correct answer: Generating unique values so test data doesn't collide
Unique emails or names on each run avoid
409 Conflicterrors and leftover data clashes.52. How do you test that an API validates enum values?
Correct answer: Send a value outside the allowed list and expect a 400
Also check case sensitivity (
PAIDvspaid) and that error messages list allowed values.53. Why check that error responses have the right
Content-Type?Correct answer: Clients parse errors by type; HTML errors break JSON clients
Proxies and frameworks often return HTML error pages. A JSON client then fails with a parse error instead of showing the message.
54. What is the benefit of running API tests against a preview environment per pull request?
Correct answer: Bugs are caught before merge, against the exact change
Each change gets its own deployment, so tests don't fight over a shared staging and failures point to the change.
55. How do you test eventual consistency between two services after an API call?
Correct answer: Poll the second service until the change appears, with a timeout
Polling with a limit is stable and fails clearly when the change never arrives. Fixed sleeps are slow and flaky.
56. What should you test about a search endpoint's filters?
Correct answer: Combinations, empty results, bad values and injection
Filters combine with AND or OR as documented, invalid values give 400, and user input can't change the query logic.
57. What does compression like
Content-Encoding: gzipmean for API tests?Correct answer: Clients must decode it; tests check headers and correct content
Most HTTP clients decode automatically. Tests check large responses are compressed and that
Accept-Encodingis respected.58. Why test an API with an old client version after a release?
Correct answer: Mobile and partner apps update slowly but must keep working
Running an older SDK or recorded requests against the new server catches breaking changes before users report them.
59. What is the role of mocks like MSW for frontend tests of API errors?
Correct answer: They let the UI be tested against 500s, timeouts and edge data
Mocking network responses in the browser or Node shows how the UI handles errors without changing the backend.
60. What should you check when an API returns lists of items?
Correct answer: Item structure, count, order, limits and total fields
Bugs often hide in later items: nulls, missing fields, wrong types for some records.
61. How should a test handle values generated by the server, like IDs and timestamps?
Correct answer: Check their format and use them, not compare to fixed values
Assert an ID is a UUID or positive integer and a timestamp is recent and valid, then use them in later requests.
62. What does API fuzzing do?
Correct answer: Sends many random or malformed inputs to find crashes
Fuzzers find unhandled exceptions, 500s and hangs that hand-written cases miss. Schema-aware fuzzers generate valid-looking inputs.
63. What does Schemathesis do?
Correct answer: Generates test cases from an OpenAPI or GraphQL schema
It uses property-based testing to find inputs that break the API or responses that don't match the spec.
64. How do you test that deleting a parent resource handles its children?
Correct answer: Check children are deleted, kept or blocked as documented
Orphaned records or a 500 because of foreign keys are common bugs after
DELETEon parents.65. Why log full requests and responses in failing API test reports?
Correct answer: Failures can be understood without rerunning the test
Mask tokens and personal data, but keep method, URL, headers and bodies so the cause is visible from the report.
66. What is the main value of a smoke collection run after each deploy?
Correct answer: Detecting a broken deploy within minutes
A few calls to critical endpoints (auth, main read, main write) catch configuration and deployment mistakes fast.
67. How do you test API behaviour when a downstream service returns invalid JSON?
Correct answer: Stub the dependency with broken JSON and check the error handling
The API should return a clear 502 or fallback, log the problem and not crash or return garbage.
68. Why test timeouts on the client side of an API integration?
Correct answer: A hanging dependency shouldn't block users forever
Without timeouts, one slow partner can exhaust connection pools. Tests with delayed stubs check limits and messages.
69. What should you test about retries in an API client?
Correct answer: Only safe or idempotent calls retry, with backoff and a limit
Retrying a non-idempotent POST can duplicate orders. Backoff with jitter avoids hammering a struggling service.
70. How can you test an API's behaviour under a dependency outage without breaking staging?
Correct answer: Use service virtualization or fault injection for that test only
Isolated fault injection keeps other teams' tests working while you check fallbacks and error codes.
71. What does
405 Method Not Allowedrequire from the server?Correct answer: An
Allowheader listing the supported methodsTesters send unsupported methods (e.g.
DELETEon a read-only endpoint) and check405withAllow, not404or500.72. What does
406 Not Acceptablemean?Correct answer: The server can't produce any format listed in
AcceptIf a client sends
Accept: application/xmlto a JSON-only API,406is the honest answer. Many APIs ignoreAcceptinstead; testers check what's documented.73. Why check that field naming is consistent, e.g. camelCase everywhere?
Correct answer: Mixed styles confuse clients and cause mapping bugs
userIdin one endpoint anduser_idin another leads to fields silently read as undefined. Style guides and linters on the OpenAPI spec help.74. How do you test that a list endpoint doesn't show soft-deleted items?
Correct answer: Delete an item, then check lists, search and counts
Soft deletes set a flag instead of removing rows. Every query must filter on it, and one forgotten filter brings deleted data back.
75. What does
Retry-Afteron a503response tell clients?Correct answer: When it's reasonable to try the request again
It can be seconds or a date. Good clients wait at least that long; tests check the header is present during maintenance or overload.