An API is a contract you cannot renegotiate cheaply
Once clients integrate, every breaking change is someone else's outage. Good API design is therefore mostly about predictability: consistent naming, consistent errors, consistent pagination. Boring is a compliment here.
REST ground rules that actually matter
- Resources are nouns:
GET /users/42/orders, not/getUserOrders. Collections plural, hierarchy reflects ownership. - Methods carry semantics: GET (safe, cacheable, no side effects), POST (create/process), PUT (full replace, idempotent), PATCH (partial update), DELETE. Misusing GET for state changes breaks caches, prefetchers and retry logic.
- Status codes tell the truth: 200 OK, 201 created, 204 no content, 400 bad input, 401 unauthenticated, 403 unauthorized, 404 missing, 409 conflict, 429 rate limited, 500 your fault. Returning 200 with an error body defeats every retry and monitoring tool in the chain.
- Errors are structured: a stable shape like
{error: {code: "card_declined", message: "...", request_id: "..."}}so clients can handle programmatically and support can trace.
Pagination: the detail everyone underestimates
Offset (?page=5&limit=50): simple, but OFFSET 100000 makes the DB scan and discard 100k rows: deep pages get slower linearly, and inserts during pagination cause duplicates/skips. Cursor (?after=order_8123&limit=50): the client passes the last seen ID; the query is WHERE id > X ORDER BY id LIMIT 50: O(1) at any depth, stable under inserts. Use offset for small admin tables, cursors for feeds and anything big.
Idempotency: the payments-grade requirement
Client taps Pay, request times out, client retries. Without protection: double charge. The pattern: the client generates a unique idempotency key per logical operation; the server stores it with the result; a retry with the same key returns the stored result instead of re-executing. Stripe popularized this; every mutating endpoint that can be retried needs it (payments, order creation, booking). GETs are naturally idempotent; POSTs are not.
Versioning and evolution
The cheapest versioning is never breaking: only add fields and endpoints, never remove or rename; clients ignore what they do not know. When a true break is unavoidable: /v1/... in the URL (simple, cache-friendly) or a version header, with the old version maintained for a deprecation window and sunset headers announcing the end date.
Worked example: an orders API
POST /orders (idempotency key required, returns 201 + order), GET /orders?after=...&limit=50 (cursor), GET /orders/123, POST /orders/123/cancel (action as sub-resource since it does not fit CRUD), errors in the stable shape above, 429s with Retry-After, /v1 prefix from day one.
Common interview traps
- 200-with-error-body responses.
- No pagination, or offset pagination on a firehose.
- Retryable mutating endpoints without idempotency keys.
- Verbs in URLs and one-off naming conventions per endpoint.
Interview Q&A
Q: PUT vs PATCH?
A: PUT replaces the whole resource and is idempotent (send it twice, same result). PATCH applies a partial change and may not be idempotent. For APIs clients retry, prefer idempotent operations or idempotency keys.
Q: How do you keep webhooks reliable as an API surface?
A: Sign payloads (HMAC), deliver with retries + exponential backoff, make events idempotent (event IDs), provide a replay endpoint, and document ordering (usually not guaranteed, events carry timestamps and full state).
API ek contract hai jise sasti mein renegotiate nahi kar sakte
Ek baar clients integrate ho gaye, to har breaking change kisi aur ka outage hai. Accha API design isliye mostly predictability ke baare mein hai: consistent naming, consistent errors, consistent pagination. Yahan "boring" tareef hai.
REST ground rules jo sach mein matter karte hain
- Resources nouns hain:
GET /users/42/orders, na ki/getUserOrders. Collections plural, hierarchy ownership dikhaye. - Methods ka matlab hota hai: GET (safe, cacheable, no side effects), POST (create/process), PUT (full replace, idempotent), PATCH (partial update), DELETE. State change ke liye GET use karna caches, prefetchers aur retry logic tod deta hai.
- Status codes sach bolein: 200 OK, 201 created, 204 no content, 400 bad input, 401 unauthenticated, 403 unauthorized, 404 missing, 409 conflict, 429 rate limited, 500 tumhari galti. 200 ke saath error body dena chain mein aane wale har retry aur monitoring tool ko bekaar karta hai.
- Errors structured hon: stable shape jaise
{error: {code: "card_declined", message: "...", request_id: "..."}}taaki clients programmatically handle karein aur support trace kar sake.
Pagination: wo detail jo sab underestimate karte hain
Offset (?page=5&limit=50): simple, par OFFSET 100000 matlab DB 100k rows scan karke phenke: deep pages linearly slow, aur pagination ke dauran inserts se duplicates/skips. Cursor (?after=order_8123&limit=50): client last seen ID deta hai; query hoti hai WHERE id > X ORDER BY id LIMIT 50: kisi bhi depth par O(1), inserts ke saath stable. Chhoti admin tables ke liye offset, feeds aur kuch bhi bada ho to cursors.
Idempotency: payments-grade zaroorat
Client ne Pay dabaya, request timeout hui, client ne retry kiya. Bina protection ke: double charge. Pattern: client har logical operation ke liye unique idempotency key banata hai; server use result ke saath store karta hai; same key wali retry ko re-execute karne ki jagah stored result milta hai. Stripe ne isse mashhoor kiya; har mutating endpoint jo retry ho sakta hai usse chahiye (payments, order creation, booking). GETs naturally idempotent hain; POSTs nahi.
Versioning aur evolution
Sabse sasta versioning hai kabhi break na karna: sirf fields aur endpoints add karo, kabhi remove ya rename nahi; clients jo nahi jaante use ignore karte hain. Jab asli break unavoidable ho: URL mein /v1/... (simple, cache-friendly) ya version header, purana version deprecation window tak zinda, sunset headers end date announce karte hue.
Worked example: orders API
POST /orders (idempotency key required, 201 + order), GET /orders?after=...&limit=50 (cursor), GET /orders/123, POST /orders/123/cancel (action as sub-resource kyunki CRUD mein fit nahi hota), errors stable shape mein, 429s Retry-After ke saath, day one se /v1 prefix.
Common interview traps
- 200-with-error-body responses.
- Pagination nahi, ya firehose par offset pagination.
- Retryable mutating endpoints bina idempotency keys ke.
- URLs mein verbs aur har endpoint par alag naming convention.
Interview Q&A
Q: PUT vs PATCH?
A: PUT poora resource replace karta hai aur idempotent hai (do baar bhejo, same result). PATCH partial change apply karta hai aur idempotent na bhi ho. Jis API ko clients retry karte hain, wahan idempotent operations ya idempotency keys prefer karo.
Q: Webhooks ko API surface ke roop mein reliable kaise rakhte ho?
A: Payloads sign karo (HMAC), retries + exponential backoff ke saath deliver karo, events idempotent banao (event IDs), replay endpoint do, aur ordering document karo (usually guaranteed nahi, events timestamps aur full state lete hain).