API Design 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. 1. How would you model 'cancel an order' in a REST API?

    Correct answer: As a state change via PATCH or a custom action

    Cancelling usually keeps the order for history and may have business rules. A dedicated action makes those rules explicit; GET must never change state.

  2. 2. When should a relationship be its own resource, like /users/42/memberships?

    Correct answer: When it has its own data or lifecycle

    Treating a membership as a resource gives you natural create, update and delete operations on it.

  3. 3. How should a JSON Merge Patch request treat null?

    PATCH /users/42
    Content-Type: application/merge-patch+json
    
    { "nickname": null, "city": "Kyiv" }

    Correct answer: null removes the field; missing fields stay as they are

    Merge Patch (RFC 7396) can't set a value to literal null or edit array elements; JSON Patch (RFC 6902) can, with explicit operations.

  4. 4. What does JSON Patch (RFC 6902) look like?

    Correct answer: A list of op/path/value operations

    Operations include add, remove, replace, move, copy and test. It's precise for arrays but more complex for clients.

  5. 5. How can a REST API let clients load related resources in one request?

    Correct answer: With a parameter like ?include=author,comments

    Expansion avoids chatty clients while keeping default responses small. Limit how deep and how many relations can be included.

  6. 6. What does sparse fieldsets (?fields=id,name,email) give clients?

    Correct answer: Only the requested fields, a smaller payload

    Google APIs use fields masks; JSON:API defines fields[type]. It helps mobile clients on slow networks.

  7. 7. Why might an API use UUIDs or opaque string IDs instead of auto-increment integers in URLs?

    Correct answer: They don't reveal counts or let anyone guess IDs

    Opaque IDs are not a security measure by themselves; authorization checks are still required on every access.

  8. 8. How should an API represent money?

    Correct answer: As integer minor units plus a currency code

    Floats lose precision. Formatting belongs in the UI, based on the user's locale.

  9. 9. How should validation errors for several fields be reported?

    {
      "type": "https://api.example.com/errors/validation",
      "title": "Invalid request",
      "status": 400,
      "errors": [
        { "field": "email", "code": "invalid_format" },
        { "field": "age", "code": "too_small", "min": 18 }
      ]
    }

    Correct answer: In one response listing all failing fields

    Problem Details allows extension members like errors. Codes let clients translate messages themselves.

  10. 10. Why should error codes in the body be stable and documented?

    Correct answer: Clients branch on them, so changes break logic

    Messages can change and be translated; codes are the contract.

  11. 11. What's the right status for a request that's well-formed but violates a business rule, like 'can't ship an unpaid order'?

    Correct answer: Usually 409 Conflict or 422 Unprocessable Content

    Pick a convention and use it across the API. The body explains the rule that failed.

  12. 12. Should an API return 403 or 404 when a user requests another user's private resource?

    Correct answer: Often 404, so existence isn't revealed

    Either way, the server must check ownership on every request; status codes don't replace authorization.

  13. 13. Why does offset pagination produce duplicates or gaps when items are inserted while paging?

    Correct answer: New items shift the positions of all later ones

    Cursor pagination based on a stable sort key (e.g. createdAt, id) doesn't have this problem.

  14. 14. Why is returning a total count with every page sometimes a problem?

    Correct answer: Counting rows can be expensive on large tables

    Many UIs only need 'is there a next page?', which cursor pagination answers cheaply.

  15. 15. What's important for a cursor-paginated list's sort order?

    Correct answer: It must be deterministic, with a tiebreaker

    Without a unique tiebreaker, items with equal timestamps can be skipped or repeated across pages.

  16. 16. How can an API offer flexible filtering without becoming a query language nobody can optimize?

    Correct answer: Support a defined set of indexed fields and operators

    Unbounded filters lead to slow queries and denial of service. Google's AIP-160 defines a constrained filter syntax.

  17. 17. How should sort parameters usually look?

    Correct answer: Allowed fields, like ?sort=-createdAt,name

    Allow only indexed fields, and validate input to avoid injection into queries.

  18. 18. How does an idempotency key work on the server?

    Correct answer: Repeats with the same key return the stored response

    Keys expire after some time. If the same key comes with a different body, return an error, since it's likely a client bug.

  19. 19. Two clients edit the same document. How can an API prevent one from silently overwriting the other?

    Correct answer: Optimistic concurrency with If-Match: <etag>

    The client then reloads, merges or asks the user. 428 Precondition Required can force clients to send If-Match.

  20. 20. What does 304 Not Modified save?

    Correct answer: Bandwidth: no body is sent

    Generating the ETag may still require loading data; cheap ETags (version numbers, update timestamps) make it worthwhile.

  21. 21. Why are retries dangerous for non-idempotent operations without protection?

    Correct answer: A lost response makes a retry repeat the work

    Timeouts don't tell the client whether the work happened. Idempotency keys or natural unique constraints make retries safe.

  22. 22. What does Cache-Control: private, max-age=60 mean?

    Correct answer: Only the user's browser may cache it, for 60 seconds

    Use public (or s-maxage) for shared caches and no-store for sensitive data that must never be stored.

  23. 23. What's the difference between no-cache and no-store?

    Correct answer: no-cache revalidates; no-store forbids storing

    Despite its name, no-cache works well with ETags: the client asks, and the server can reply 304.

  24. 24. What does stale-while-revalidate allow?

    Correct answer: Serving a stale copy while refreshing in the background

    It hides revalidation latency from users. stale-if-error serves stale data when the origin fails.

  25. 25. Why is the Vary header important for caching API responses?

    Correct answer: It lists the request headers that change the response

    Missing Vary can make a CDN serve a German response to an English user, or one user's data to another.

  26. 26. What counts as a breaking change in a REST API?

    Correct answer: Removing or renaming fields, changing types

    Adding optional request fields, new endpoints or new response fields is normally safe.

  27. 27. What is Hyrum's Law?

    Correct answer: Someone will depend on every observable behavior

    Field order, timing and undocumented defaults all become de facto contracts. Be careful even with 'internal' changes.

  28. 28. What are trade-offs of URL versioning (/v2/...) versus header versioning?

    Correct answer: URLs are visible and cacheable; headers keep URLs stable

    Some APIs (Stripe) version by date per account, letting each client upgrade on its own schedule.

  29. 29. How can you evolve a field's format without a new major version?

    Correct answer: Add a new field and deprecate the old one

    Expand and contract works for APIs as for databases. Track usage of the deprecated field before removal.

  30. 30. What's the difference between authentication and authorization in an API?

    Correct answer: Authentication is who; authorization is what's allowed

    Most API breaches come from broken authorization: authenticated users accessing objects or functions they shouldn't.

  31. 31. What does OWASP API1:2023 Broken Object Level Authorization describe?

    Correct answer: No check that the user may access the given object ID

    Changing /accounts/123 to /accounts/124 should never reveal someone else's account. Check ownership in every handler.

  32. 32. What is Broken Object Property Level Authorization (OWASP API3:2023)?

    Correct answer: Exposing or accepting properties the user shouldn't touch

    Use explicit response models and input allow-lists instead of returning or binding whole objects.

  33. 33. Why should access tokens be short-lived?

    Correct answer: A leaked token can then be used only briefly

    Self-contained JWTs are hard to revoke, so short lifetimes limit the damage.

  34. 34. What are OAuth scopes used for?

    Correct answer: Limiting what a token may do

    Scopes express what the client is allowed to do on the user's behalf; the API still checks the user's own permissions.

  35. 35. How should service-to-service calls inside a system be authenticated?

    Correct answer: With machine credentials like mTLS or signed tokens

    Zero-trust thinking: an attacker inside the network shouldn't automatically reach every service.

  36. 36. Why should rate limits be applied per client (API key or user) rather than only per IP?

    Correct answer: Many users share one IP, and attackers rotate them

    Combine both: per-IP limits for anonymous traffic, per-key or per-user limits for authenticated calls.

  37. 37. What does OWASP API4:2023 Unrestricted Resource Consumption cover?

    Correct answer: Missing limits on rate, payload size or expensive work

    It also covers paid third-party resources: an endpoint that sends SMS without limits can run up a huge bill.

  38. 38. What's a good client behavior when it receives 429 or 503?

    Correct answer: Respect Retry-After, or use backoff with jitter

    Synchronized immediate retries from many clients make outages worse.

  39. 39. How should a webhook receiver verify that a request really comes from the provider?

    Correct answer: Check an HMAC signature over body and timestamp

    Compute the signature over the raw bytes (before JSON parsing) and compare in constant time. Standard Webhooks defines a common scheme.

  40. 40. Why should webhook handlers be idempotent?

    Correct answer: Providers retry, so events can repeat

    Store processed event IDs, or make the effect naturally idempotent (e.g. set status rather than increment).

  41. 41. Why should a webhook endpoint respond quickly and process the event asynchronously?

    Correct answer: Providers time out quickly and then retry

    Return 2xx once the event is safely recorded; then process it in the background.

  42. 42. Can webhook events be assumed to arrive in order?

    Correct answer: No; retries and parallel delivery reorder them

    A common pattern is 'thin' events: the webhook says what changed, and the receiver fetches the current object.

  43. 43. Why is HTTP caching harder with GraphQL than with REST?

    Correct answer: Queries usually go as POST to a single URL

    GraphQL clients like Apollo or Relay cache normalized objects on the client instead.

  44. 44. How do GraphQL errors differ from REST errors?

    Correct answer: A response can mix partial data and errors

    Some teams model expected business errors as part of the schema (union result types) instead of using errors.

  45. 45. How does GraphQL usually handle schema evolution?

    Correct answer: Adding fields and marking old ones @deprecated

    Field usage metrics show when a deprecated field can be removed safely.

  46. 46. When is tRPC a good choice?

    Correct answer: For TypeScript full-stack apps in one repo

    tRPC gives end-to-end types without code generation, but couples clients to the TypeScript server.

  47. 47. What does AsyncAPI describe?

    Correct answer: Event-driven and message-based APIs

    It's to message APIs what OpenAPI is to HTTP APIs: docs, code generation and contract checks.

  48. 48. How should an API handle a bulk operation where some items fail?

    Correct answer: Return per-item results with success or error

    Some APIs use 207 Multi-Status; others return 200 with a results array. Document whether the operation is atomic.

  49. 49. Why might a large export be better as an asynchronous job than a single GET?

    Correct answer: It can exceed timeouts and memory limits

    Presigned URLs let clients download large files directly from object storage.

  50. 50. How can clients upload large files without sending them through the API server?

    Correct answer: The API issues a presigned URL for object storage

    The API keeps control (who may upload, size limits, content type) without carrying the bytes.

  51. 51. What makes API documentation genuinely useful?

    Correct answer: Accurate reference plus guides and examples

    Runnable examples and a sandbox environment shorten integration time a lot.

  52. 52. How can you catch breaking changes in an OpenAPI spec automatically?

    Correct answer: Run a spec diff tool like oasdiff in CI

    Combine with linting (Spectral) for style rules and contract tests to check that the implementation matches the spec.

  53. 53. What are contract tests between a client and an API?

    Correct answer: Tests that both sides agree on requests and responses

    They catch incompatibilities earlier than full end-to-end tests and run faster.

  54. 54. Why generate SDKs or clients from an OpenAPI spec?

    Correct answer: Typed clients stay in sync with the API

    The quality of generated code depends on the spec: good names, examples and accurate schemas matter.

  55. 55. How should an API handle time zones in inputs and outputs?

    Correct answer: Use UTC timestamps; accept the user's zone apart

    Calendar-style data (birthdays, opening hours) may need dates without times or explicit IANA zones like Europe/Kyiv.

  56. 56. What's a sensible default for unknown query parameters?

    Correct answer: Reject them with 400, so typos don't go unnoticed

    Silent ignoring hides client bugs. Many guidelines prefer strict validation.

  57. 57. Why should list responses have a stable default sort order?

    Correct answer: Row order can vary, which breaks pagination

    A default like newest first (with an ID tiebreaker) keeps results predictable.

  58. 58. What does a 'Backend for Frontend' change about API design?

    Correct answer: Each client type gets an API shaped for its screens

    BFFs reduce chattiness for mobile apps and let teams change UI-specific APIs without affecting other clients.

  59. 59. What does an API gateway typically handle?

    Correct answer: Routing, authentication and rate limiting

    Keep business rules in services; a gateway that grows too smart becomes a bottleneck and a single point of coupling.

  60. 60. How should an API expose actions on many items, like 'archive 500 messages'?

    Correct answer: With a size-limited batch endpoint

    Batch endpoints reduce overhead; limits and async processing protect the server.

  61. 61. Why include a correlation ID in error responses?

    Correct answer: So support can find the exact request in logs

    Problem Details' instance field or a custom traceId field can carry it.

  62. 62. What's the risk of exposing internal error messages (e.g. SQL errors) to API clients?

    Correct answer: They leak implementation details to attackers

    Security misconfiguration (OWASP API8) includes verbose error messages.

  63. 63. When might PUT with a full document be better than PATCH?

    Correct answer: When clients always hold the full resource

    Combine PUT with If-Match to avoid overwriting someone else's changes.

  64. 64. Why should API responses avoid exposing nulls for fields that are 'not applicable' vs 'unknown' without documentation?

    Correct answer: Clients can't tell missing, empty and null apart

    Decide whether absent and null differ, and document it, especially for PATCH semantics.

  65. 65. What is media type versioning?

    Correct answer: Clients request a version through the Accept header

    It keeps URLs stable and uses content negotiation, but it's harder to try in a browser and to route in some gateways.

  66. 66. What does the Prefer: return=minimal request header ask for?

    Correct answer: That the server omit the full resource in its reply

    return=representation asks for the full updated resource instead. The server reports what it applied with Preference-Applied.

  67. 67. Why can't an API respond with Access-Control-Allow-Origin: * to credentialed browser requests?

    Correct answer: Browsers reject the wildcard with credentials

    Echo only origins from an allow list, and add Vary: Origin so caches don't mix responses for different origins.

  68. 68. A browser SPA authenticates with cookies to its API. What extra protection is needed compared with bearer tokens?

    Correct answer: CSRF protection: SameSite cookies plus a token

    Browsers attach cookies automatically, even to requests triggered by other sites. Bearer tokens in headers aren't sent automatically.

  69. 69. How should an API provider store the API keys it issues?

    Correct answer: Store only a hash, and show the full key once

    Prefixes like sk_live_ make leaked keys easy to detect by secret scanners and help users know which key is which.

  70. 70. When is POST /orders/search with a JSON body acceptable instead of GET with query parameters?

    Correct answer: When filters are too long or sensitive for a URL

    The trade-off: POST responses aren't cached by default and the operation looks non-idempotent. Document it clearly.

  71. 71. What is the /users/me (or /me) convention for?

    Correct answer: Accessing the signed-in user's own resource

    The server resolves me from the token, which avoids clients guessing or tampering with IDs.

  72. 72. When should an API return 410 Gone rather than 404?

    Correct answer: When it was intentionally and permanently removed

    410 tells clients and crawlers to stop asking. It's useful after an endpoint's sunset date.

  73. 73. What status fits a request body larger than the API allows?

    Correct answer: 413 Content Too Large

    Document limits and reject large bodies early, before reading them fully into memory.

  74. 74. Why does a stable operationId in OpenAPI matter?

    Correct answer: Generators use it for SDK method names

    Treat operation IDs and schema names as part of the public contract when you publish SDKs.

  75. 75. How should webhook payloads be versioned?

    Correct answer: Include an event type and version in each event

    Webhook consumers are API clients too; breaking changes in event shapes need the same care as endpoint changes.