API design basics: 50 cards on REST, status codes and auth
API design fundamentals: REST, HTTP methods, status codes, pagination, versioning, OAuth 2.0 and JWT, CORS, OpenAPI, GraphQL, gRPC and webhooks.
Practice now
Study without an account
Scheduled with the default Askesis timings. Progress is saved in this browser.
All 50 cards
- 1What is REST?An architectural style for networked APIs, described by Roy Fielding in 2000: resources identified by URLs and manipulated through a uniform interface of standard HTTP methodsIts constraints: client-server, stateless, cacheable, uniform interface, layered system, and optional code on demand.
- 2How should REST endpoints be named?Nouns for resources, plural for collections, and HTTP methods for the action:
GET /users,GET /users/42,POST /users/42/ordersAvoid verbs in paths, like/getUseror/createOrder. - 3What does “stateless” mean for a REST API?Each request carries everything the server needs to handle it, such as the auth token; the server keeps no client session between requestsAny server instance can then handle any request, which makes scaling out easy.
- 4HATEOASHypermedia as the engine of application state: responses include links to related resources and available actions, so clients follow links instead of hard-coding URLsIt’s the strictest REST constraint and is rarely implemented in full.
- 5Filtering, sorting and selecting fields in a REST APIQuery parameters on the collection, e.g.
GET /orders?status=shipped&sort=-created_at&fields=id,total - 6What do GET, POST, PUT, PATCH and DELETE do?GET reads, POST creates (or triggers processing), PUT replaces, PATCH partially updates, DELETE removes
- 7Which HTTP methods are safe?GET, HEAD and OPTIONS (and TRACE): they must not change server stateCrawlers and link prefetchers assume safe methods are harmless, so never let a GET delete or modify data.
- 8Which HTTP methods are idempotent?GET, HEAD, OPTIONS, PUT and DELETE. POST is not, and PATCH isn’t guaranteed to beIdempotency is about server state, not the response: a repeated DELETE may return 404 and is still idempotent.
- 9PUT vs PATCHPUT replaces the whole resource with the request body; PATCH applies a partial change, such as updating only the fields sentCommon PATCH formats are JSON Merge Patch (RFC 7396) and JSON Patch (RFC 6902).
- 10Creating a resource: POST vs PUT
POST /userswhen the server assigns the ID;PUT /users/alicewhen the client chooses the URL (PUT creates or replaces) - 11The five classes of HTTP status codes1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error
- 12200 vs 201 vs 204200 OK, with a response body. 201 Created, usually with a
Locationheader pointing to the new resource. 204 No Content: success with an empty body - 13400 vs 422400 Bad Request: the request is malformed, e.g. invalid JSON. 422 Unprocessable Content: it’s well-formed but fails validationMany APIs use 400 for both; pick one convention and document it.
- 14401 vs 403401 Unauthorized: not authenticated (credentials missing or invalid). 403 Forbidden: authenticated, but not allowed to do thisDespite its name, 401 is about authentication. Some APIs answer 404 instead of 403 to avoid revealing that a resource exists.
- 15404 vs 405404 Not Found: nothing exists at this URL. 405 Method Not Allowed: the resource exists but doesn’t support this method, and the response must list the allowed ones in an
Allowheader - 16When should an API return 409 Conflict?When the request conflicts with the resource’s current state, e.g. signing up with a username that’s taken, or updating a record that changed in the meantime
- 17500 vs 502 vs 503 vs 504500: an unexpected server error. 502 Bad Gateway: a proxy got an invalid response from upstream. 503 Service Unavailable: overloaded or down for maintenance. 504 Gateway Timeout: the upstream didn’t answer in time
- 18How do ETags make repeated GET requests cheaper?The server sends an
ETag(a version tag); the client sends it back inIf-None-Match, and if nothing changed the server answers304 Not Modifiedwith no body - 19How do you prevent lost updates when two clients edit the same resource?Optimistic concurrency: send
If-Matchwith the ETag you read. If the resource changed since then, the server rejects the write with412 Precondition FailedWithout such a check, the last write silently overwrites the other client’s changes. - 20Standard format for API error responsesProblem Details (RFC 9457): a JSON body served as
application/problem+jsonjson{ "type": "https://example.com/errors/out-of-credit", "title": "You do not have enough credit.", "status": 403, "detail": "Your balance is 30, but that costs 50." } - 21Offset vs cursor paginationOffset (
?limit=20&offset=40) is simple and can jump to any page, but slows down at large offsets and skips or repeats items when data changes. Cursor (?limit=20&after=abc123) is fast and stable, but only moves to the next or previous page - 22Keyset (cursor) pagination in SQLsql
SELECT * FROM posts WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 20;The cursor encodes the sort key of the last row returned. Includingidbreaks ties, and an index on(created_at, id)keeps every page fast. - 23How do API clients find the next page?Return a cursor or URL for the next page in the body (e.g.
"next_cursor": "abc123"), or aLinkheader withrel="next", as GitHub doesLeave the cursor out (or null) on the last page so clients know when to stop. - 24Three common ways to version an APIIn the URL path (
/v1/users), in a header (e.g.Accept: application/vnd.example.v2+json), or as a query parameter (?version=2)Path versioning is the most common because it’s explicit and easy to route, cache and test. - 25Breaking vs non-breaking API changesBreaking: removing or renaming fields, changing types or meanings, adding required parameters. Non-breaking: adding endpoints, optional parameters or new response fieldsNew fields are only safe if clients ignore fields they don’t recognize, so tell them to.
- 26How do you retire an old API version gracefully?Announce a timeline, flag it in responses with
DeprecationandSunsetheaders, watch who still calls it, and only then switch it offTheSunsetheader (RFC 8594) gives the date the endpoint will stop working. - 27Authentication vs authorizationAuthentication checks who you are; authorization decides what you’re allowed to do
- 28When do API keys fit, and how should they be sent?For identifying a calling application or project, e.g. server-to-server calls and usage metering. Send them in a header, never in the URLAn API key identifies an app, not a user, and can’t express a user’s consent; use OAuth for delegated access.
- 29What problem does OAuth 2.0 solve?Delegated authorization: a user lets an app access their data at another service, limited by scopes, without giving the app their passwordThe app receives an access token and sends it with each call as
Authorization: Bearer <token>. - 30The four OAuth 2.0 rolesResource owner (the user), client (the app), authorization server (issues tokens), resource server (the API that accepts them)
- 31Which OAuth 2.0 flow should web, mobile and single-page apps use?Authorization code with PKCE: the user signs in at the authorization server, and the app exchanges the short-lived code it gets back, together with a secret code verifier, for tokensPKCE stops an intercepted code from being redeemed by an attacker. The older implicit flow is deprecated.
- 32OAuth 2.0 flow for machine-to-machine calls with no userClient credentials: the service authenticates with its own client ID and secret to get an access token
- 33OAuth 2.0 vs OpenID ConnectOAuth 2.0 handles authorization (access tokens for APIs). OpenID Connect adds an identity layer on top, with an ID token (a JWT) saying who signed in“Sign in with Google” uses OpenID Connect.
- 34Structure of a JWTThree base64url parts joined by dots,
header.payload.signature. The payload holds claims such assub,exp,issandaudA typical JWT is signed, not encrypted: anyone can decode and read the payload, so never put secrets in it. - 35What must a server check when it receives a JWT?The signature, using the algorithm it expects (never accept
alg: none), plus the expiry (exp), the issuer (iss) and the audience (aud) - 36Access token vs refresh tokenAccess tokens are short-lived (minutes) and sent with every API call. Refresh tokens live longer and are sent only to the authorization server, to get new access tokensShort lifetimes limit the damage of a leaked token, because a self-contained JWT can’t easily be revoked before it expires.
- 37What is CORS?Cross-Origin Resource Sharing: a way for a server to tell browsers which other origins may read its responses, using headers such as
Access-Control-Allow-OriginAn origin is scheme + host + port. Without CORS headers, the browser’s same-origin policy stops scripts from reading cross-origin responses. - 38When does a browser send a CORS preflight request?Before a cross-origin request that isn’t “simple”, e.g.
PUTorDELETE, aContent-Type: application/jsonbody, or custom headers. It sendsOPTIONSto ask whether that method and those headers are allowedAccess-Control-Max-Agelets the browser cache the answer. - 39CORS rules for requests that send cookiesThe server must send
Access-Control-Allow-Credentials: trueand name the exact origin;Access-Control-Allow-Origin: *isn’t allowed with credentialsOnly browsers enforce CORS. It doesn’t protect an API from curl or other servers; that’s the job of authentication. - 40How should an API tell clients they hit a rate limit?Respond with
429 Too Many Requestsand aRetry-AfterheaderMany APIs also send headers likeX-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Reset, so clients can slow down before they hit the limit. - 41How do you make
POST /paymentssafe to retry?The client sends a uniqueIdempotency-Keyheader; the server stores the first result for that key and returns it for any retry instead of charging againStripe popularized this pattern, and the IETF is standardizing the header. - 42What is OpenAPI?A standard, machine-readable format (YAML or JSON) for describing HTTP APIs: endpoints, parameters, request and response schemas, and authenticationFormerly called Swagger. One spec can drive docs, client and server code generation, request validation and mock servers.
- 43What does this OpenAPI snippet describe?yaml
paths: /users/{id}: get: parameters: - name: id in: path required: true schema: type: integer responses: "200": description: The user "404": description: No such userAGET /users/{id}endpoint with a required integer path parameterid, which responds with 200 (the user) or 404 - 44What is gRPC?An RPC framework that sends Protocol Buffers messages over HTTP/2. Services are defined in
.protofiles that generate typed clients and servers, with streaming in either or both directionsFast and strongly typed, it’s popular between internal services. Browsers can’t call it directly and need a bridge such as gRPC-Web. - 45What is GraphQL?A query language for APIs: clients send queries to a single endpoint and get back exactly the fields they asked for, checked against a typed schemaIt avoids over-fetching (too much data) and under-fetching (several round trips), but makes HTTP caching and rate limiting harder.
- 46REST vs GraphQL vs gRPC: which fits?REST for public, resource-oriented, cacheable APIs; GraphQL when varied clients need flexible, nested data in one request; gRPC for fast, typed service-to-service calls and streaming
- 47The N+1 problem in GraphQLResolving a list and then a field on each item runs one query for the list plus one more per itemBatch and cache those lookups per request with a DataLoader.
- 48What is a webhook?An HTTP callback: when an event happens, the provider sends a POST to a URL you registered, so you don’t have to poll for changes
- 49How do you verify that a webhook really came from the provider?Check its signature: compute an HMAC of the raw request body with the shared secret and compare it, in constant time, with the signature header, such as GitHub’s
X-Hub-Signature-256Also reject old timestamps to block replayed requests, and accept webhooks only over HTTPS. - 50Best practices for receiving webhooksReturn a 2xx quickly and do the work asynchronously, deduplicate by event ID because providers retry, and don’t assume events arrive in order
Frequently asked questions
Is REST still the default choice for APIs?
For public and resource-oriented APIs, yes: it works with every HTTP client, caches well and is easy to explore. GraphQL and gRPC fit specific needs, such as flexible client queries or fast internal calls.
Should I put the API version in the URL?
URL versioning like /v1/ is the most common because it is explicit and easy to route. Header versioning keeps URLs clean but is harder to try in a browser. Either works if you avoid breaking changes within a version.
Is a JWT the same as OAuth?
No. OAuth 2.0 is a framework for obtaining access tokens, and a JWT is one token format. Many OAuth servers issue JWTs, but others use opaque tokens.
More in Computer science
Computer science
CS fundamentals: binary and hex, two’s complement, Big-O, stack vs heap, threads and deadlocks, CPU caches, compilers, UTF-8 and floating point.
50 cardsMorse code
Learn International Morse code: all 26 letters, the 10 digits, common punctuation and signals like SOS, each with its rhythm and a memory aid.
50 cardsDS & Algorithms
Big-O for arrays, hash maps, heaps, trees and graphs, sorting trade-offs, and the patterns behind interview problems: two pointers, sliding windows, BFS, Dijkstra and DP.
50 cardsDesign patterns
SOLID, DRY, KISS and YAGNI, plus the Gang of Four patterns used most: singleton, factory, builder, adapter, decorator, observer, strategy, command and more.
50 cardsSoftware testing
Software testing fundamentals: the test pyramid, unit, integration and E2E tests, TDD, mocks vs stubs vs fakes, coverage, mutation and property-based testing.
50 cardsSystem design
System design fundamentals: load balancers, caching, CDNs, replication and sharding, CAP, consistency, queues, rate limiting and back-of-the-envelope math.
50 cardsCryptography
Cryptography flashcards: AES modes, RSA, elliptic curves, Diffie–Hellman, hashing, HMAC, signatures, password hashing, TLS 1.3 and common pitfalls.
50 cards