
Frontend interviews rarely ask you to build an API. They ask whether you can consume one well: pick the right method, handle every status code, cache sensibly, paginate, authenticate, and recover from failure. These 20 questions cover what comes up in coding rounds and system design, with the answer an interviewer wants to hear.
Fundamentals
1. What makes an API RESTful?
Resources are identified by URLs, and you act on them with standard HTTP methods. The server is stateless: each request carries everything needed to process it. Responses say whether they’re cacheable, and the interface is uniform (same conventions for every resource).
2. What does each HTTP method do?
| Method | Purpose | Safe | Idempotent |
|---|---|---|---|
GET |
Read | Yes | Yes |
POST |
Create, or trigger an action | No | No |
PUT |
Replace a resource | No | Yes |
PATCH |
Update part of a resource | No | Not guaranteed |
DELETE |
Remove | No | Yes |
More in GET vs POST.
3. What is idempotency and why does the frontend care?
An idempotent request has the same effect whether it’s sent once or five times. It decides what’s safe to retry automatically. Retrying a GET or PUT is fine. Retrying a POST can create duplicates, so payment-style endpoints accept an Idempotency-Key header: the client sends a unique key and the server ignores repeats.
4. PUT vs PATCH?
PUT sends the whole resource and replaces it. PATCH sends only the fields that change. Use PATCH for forms that edit a few fields, so you don’t overwrite changes someone else made to the others.
5. Which status codes should a frontend handle?
| Code | Meaning | Typical UI response |
|---|---|---|
| 200 / 201 / 204 | OK / Created / No content | Show the result |
| 304 | Not modified | Use the cached copy |
| 400 / 422 | Bad request / validation failed | Show field errors |
| 401 | Not authenticated | Refresh the session or go to login |
| 403 | Not allowed | Explain; don’t retry |
| 404 | Not found | Empty or not-found state |
| 409 | Conflict | Offer to reload or merge |
| 429 | Rate limited | Back off, honour Retry-After |
| 5xx | Server error | Retry with backoff, then show an error |
6. 401 vs 403?
401: “I don’t know who you are.” 403: “I know who you are, and you can’t do this.”
Using an API from the browser
7. Why doesn’t fetch reject on a 404?
fetch only rejects on network failure or abort. HTTP errors resolve normally, so check res.ok:
async function getJSON(url, options) {
const res = await fetch(url, options);
if (!res.ok) {
const body = await res.json().catch(() => null);
throw Object.assign(new Error(body?.message ?? res.statusText), {
status: res.status,
body,
});
}
return res.status === 204 ? null : res.json();
}
8. How would you retry failed requests?
Only retry idempotent requests, only on network errors, 429 and 5xx, with exponential backoff and jitter, and a cap on attempts.
async function withRetry(fn, { retries = 3, base = 300 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
const retryable = !err.status || err.status === 429 || err.status >= 500;
if (!retryable || attempt === retries) throw err;
const wait = base * 2 ** attempt + Math.random() * 100;
await new Promise((r) => setTimeout(r, wait));
}
}
}
Practise it: API retry.
9. How do you cancel a request?
Pass an AbortController signal to fetch and call abort(). Essential for search-as-you-type and for cleaning up in React effects.
10. How do you avoid sending the same request twice?
Keep a map of in-flight promises keyed by URL and return the existing promise to later callers. Data libraries do this for you. Try it: merge identical API calls.
11. What is CORS?
A browser rule: a page can only read responses from another origin if that server allows it with Access-Control-Allow-Origin. Non-simple requests (custom headers, JSON content type, methods other than GET/POST/HEAD) trigger a preflight OPTIONS request first. It’s enforced by the browser, not the server, and it’s fixed on the server. See CORS.
Caching and performance
12. How does HTTP caching work?
Cache-Control: max-age=60: reuse without asking for 60 seconds.ETag+If-None-Match: ask “has it changed?” and get a tiny304if not.Cache-Control: no-store: never cache (sensitive data).stale-while-revalidate: serve the cached copy now and refresh in the background.
13. Offset vs cursor pagination?
Offset (?page=3&limit=20) |
Cursor (?after=abc&limit=20) |
|
|---|---|---|
| Jump to page N | Yes | No |
| Stable while items are added | No: duplicates or gaps | Yes |
| Cost on large tables | Grows with offset | Constant |
| Best for | Admin tables | Feeds, infinite scroll |
14. How would you reduce the number of requests a page makes?
Fetch in parallel, not in sequence. Ask for only the fields you need. Batch where the API allows. Cache and deduplicate on the client. Prefetch on hover or when idle. See data fetching strategies.
15. What’s an optimistic update?
Update the UI immediately, send the request, and roll back if it fails. It suits actions that almost always succeed, such as likes and toggles. Keep the previous value so you can restore it, and tell the user when a rollback happens.
Auth and security
16. Cookies vs bearer tokens?
HttpOnly cookies are sent automatically and can’t be read by scripts, so XSS can’t steal them, but you need CSRF protection (SameSite). Bearer tokens in an Authorization header aren’t sent automatically, so CSRF isn’t an issue, but storing them in localStorage exposes them to XSS.
17. How do you handle an expired access token?
On a 401, call the refresh endpoint once, queue other failing requests behind that single refresh, then replay them. If the refresh fails, log the user out.
18. What should never be in a URL?
Secrets and personal data. URLs end up in logs, browser history and Referer headers.
Design
19. How should errors be shaped?
Consistently. One format for every endpoint, with a machine-readable code, a human message, and field-level details for validation:
{ "error": { "code": "validation_failed", "message": "Email is invalid", "fields": { "email": "invalid_format" } } }
20. REST vs GraphQL?
REST: simple, cacheable by URL, one endpoint per resource, but you can over-fetch or need several round trips. GraphQL: the client asks for exactly the fields it needs in one request, at the cost of harder HTTP caching and more server complexity. Say which you’d pick for the product in front of you and why.
How to practise
- Build a small fetch wrapper with error handling, retry and cancellation from memory.
- Design an API for a feature out loud. API design best practices covers what interviewers expect.
- Review the web protocols cheat sheet for when REST isn’t the right tool (WebSocket, SSE).
