Web Development
Design, secure, document, test and operate HTTP APIs that clients can rely on for years.
A path through designing web APIs well: HTTP fundamentals, choosing an API style, resource and URL design, pagination and errors, authentication and authorization, documentation, security, performance, integration patterns, testing, real-time transports and compliance. Resources point to RFCs, MDN, OWASP and official tool docs.
The subjects follow the roadmap.sh API Design roadmap.
Before designing an API you need a working model of what travels over the wire: a client resolves a host name, opens a connection, sends a request with a method, path and headers, and reads back a status code and a body. Every later design decision sits on top of this.
An API is a contract that lets one program use another without knowing its internals. For web APIs that contract is a set of URLs, methods, payload shapes and error formats that clients can rely on staying stable.
Path segments identify a resource (/users/42), query parameters refine a read (?status=active&limit=20). Keep identifiers in the path, optional filters in the query, and percent-encode anything user-supplied.
Clients state what they can handle with Accept, Accept-Language and Accept-Encoding; the server picks a representation and says what it chose with Content-Type. Answer 406 or fall back to a default when nothing matches, and add Vary so caches keep variants apart.
HTTP/1.1 and HTTP/2 run over TCP, which gives ordered, reliable byte streams at the cost of a handshake per connection. Knowing this explains why keep-alive, connection pooling and TLS session reuse matter so much for API latency.
DNS turns api.example.com into IP addresses via A/AAAA records, CNAMEs and TTL-based caching. Low TTLs make failover and blue-green cutovers faster; high TTLs cut lookup latency but slow down changes.
HTTP is the protocol nearly every public API speaks. Its methods, status codes, headers and caching rules already solve many problems, so a good API leans on them instead of reinventing them inside JSON bodies.
HTTP/1.1 sends one request at a time per connection; HTTP/2 multiplexes many streams over one TCP connection with binary framing and header compression; HTTP/3 runs over QUIC on UDP to avoid TCP head-of-line blocking. The semantics stay the same across all three.
GET reads, POST creates or triggers, PUT replaces, PATCH partially updates, DELETE removes. GET, HEAD, PUT and DELETE are idempotent by definition, which tells clients and proxies what is safe to retry.
Use the code that matches what happened: 201 with a Location header after a create, 204 for an empty success, 400 vs 422 for bad input, 401 for missing credentials, 403 for insufficient rights, 409 for conflicts, 429 for throttling.
Headers carry metadata outside the body: Authorization, Content-Type, ETag, Cache-Control, Retry-After, Idempotency-Key. Prefer standard headers, and avoid the old X- prefix for new custom ones.
Browsers store Set-Cookie values and send them back automatically. For session cookies set HttpOnly, Secure and a SameSite policy; because they ride along on every request, cookie-authenticated APIs need CSRF protection.
Browsers block cross-origin reads unless the server opts in with Access-Control-Allow-Origin. Non-simple requests trigger an OPTIONS preflight; credentials require an explicit origin, never *. CORS protects users in browsers, not your server from other clients.
Cache-Control sets freshness (max-age, no-store, private), while ETag or Last-Modified let clients revalidate with If-None-Match and receive a cheap 304. Cacheable GET responses take load off your servers for free.
Resource-oriented REST, RPC frameworks, query languages and XML envelopes each make different trade-offs between flexibility, tooling, performance and how tightly client and server are coupled. Pick per audience: public APIs favour REST or GraphQL, internal service calls often favour gRPC.
REST models the domain as resources addressed by URLs and manipulated through the uniform HTTP methods. It is cacheable, easy to explore with curl, and the default choice for public HTTP APIs.
Many APIs are just JSON over HTTP without strict REST discipline: a few endpoints, POST for most actions, ad hoc shapes. Fine for small internal tools, but consistency in naming and errors still pays off.
SOAP wraps calls in XML envelopes described by a WSDL contract, with standards for security and transactions layered on top. It is verbose and mostly found in enterprise, banking and government integrations you must consume rather than build.
GraphQL exposes a typed schema and lets clients ask for exactly the fields they need in one request. It removes over- and under-fetching but moves complexity to the server: N+1 resolvers, query cost limits and harder HTTP caching.
gRPC defines services in Protocol Buffers and generates typed clients and servers. It runs over HTTP/2 with compact binary messages and built-in streaming, which suits service-to-service calls; browsers need gRPC-Web or a proxy.
Design the contract before writing handlers: list the resources, their relationships and the operations on them, then agree on URL shapes, naming and versioning. Writing the spec first lets frontend, backend and partners work in parallel and catches awkward designs while they are cheap to change.
Fielding's constraints: client-server separation, stateless requests, cacheable responses, a uniform interface, a layered system and optional code on demand. Statelessness is the one that matters most in practice, since it lets any instance serve any request.
Use plural nouns for collections (/orders), IDs for members (/orders/123) and shallow nesting for ownership (/orders/123/items). Verbs belong in the method, not the path; reserve sub-resources like /orders/123/cancel for actions that are not plain CRUD.
Pick one casing for JSON fields (camelCase or snake_case) and one for paths (lowercase kebab-case is common), then apply it everywhere. Consistent names for timestamps (createdAt), IDs and booleans make an API predictable to guess.
Version in the path (/v1/), a header, or a media type. Path versions are easy to see and route; header or date-based versions (as Stripe does) allow finer evolution. Either way, add fields freely and save new versions for breaking changes.
Map create, read, update and delete to POST /items, GET /items/{id}, PUT or PATCH /items/{id} and DELETE /items/{id}. Return the created or updated resource so clients do not need a second round trip.
Resources should reflect what clients care about, not your database tables. Decide which entities get their own URL, which are embedded, and how relationships are exposed (IDs, links or nested objects).
Real collections are large and real networks drop requests. Pagination, filtering, idempotency and linking decide whether clients can work with your data efficiently and retry safely.
Offset pagination (?page=3&limit=50) is simple but slow and unstable on large or changing tables. Cursor pagination returns an opaque next token based on a sort key, staying fast and consistent as rows are inserted.
A request is idempotent if repeating it has the same effect as sending it once. For non-idempotent POSTs, accept an Idempotency-Key header, store the first result, and replay it on retries so a timeout never charges a card twice.
Responses include links to related resources and next actions, so clients follow links instead of hard-coding URLs. Rarely implemented fully; pagination next links and Location headers are the parts most APIs adopt.
Expose filters as query parameters (?status=paid&createdAfter=...), sorting as ?sort=-createdAt, and free text as ?q=. Whitelist sortable and filterable fields so clients cannot trigger unindexed queries.
An API has to protect itself from overload and tell clients clearly what went wrong. Predictable limits and a single machine-readable error format make client code simpler and support tickets rarer.
Cap requests per key, user or IP over a window and answer 429 Too Many Requests with Retry-After. Token bucket and sliding window counters (often in Redis) are the usual algorithms; publish the limits so clients can pace themselves.
Return the right status code plus a body with a stable machine-readable code, a human message and field-level details for validation errors. Never leak stack traces or SQL, and keep the same shape across every endpoint.
A standard JSON error shape served as application/problem+json, with type, title, status, detail and instance plus your own extension fields. RFC 9457 replaced 7807 in 2023 with compatible changes.
Authentication answers who is calling. The choice depends on the client: browsers suit cookies and sessions, server-to-server calls suit keys or client credentials, and third-party access needs delegated tokens. Always require TLS, since every scheme leaks over plain HTTP.
The client sends Authorization: Basic base64(user:password) on every request. Trivial to implement but the credential is only encoded, not encrypted, and cannot be scoped or expired; acceptable only over TLS for simple internal tooling.
After login the client gets a token and sends it as Authorization: Bearer <token>. Tokens can be opaque (looked up server-side) or self-contained, and pair well with short lifetimes plus refresh tokens.
A JSON Web Token is a signed, base64url-encoded set of claims (sub, exp, aud) that servers verify without a database lookup. Pin the algorithm, check exp and aud, keep them short-lived, and remember revocation is hard.
A delegation framework: users grant an app limited access via an authorization server, which issues access tokens. Use authorization code with PKCE for user-facing apps and client credentials for machine-to-machine; the implicit flow is deprecated.
The server stores session state and gives the browser a random ID in an HttpOnly cookie. Easy to revoke and well suited to first-party web apps, but needs shared session storage when you scale out and CSRF defences.
OpenID Connect adds an identity layer to OAuth 2.0: an id_token JWT describing the user, a userinfo endpoint and discovery metadata. It is what "Sign in with Google" uses under the hood.
Authorization decides what an authenticated caller may do. Check it on every request on the server, at the object level as well as the endpoint level; broken object-level authorization is the top API vulnerability in OWASP's list.
Role-based access control assigns permissions to roles (admin, editor, viewer) and roles to users. Simple to reason about and audit, but roles tend to multiply when rules depend on ownership or context.
Attribute-based access control evaluates rules over attributes of the user, resource, action and environment, such as department, owner or time of day. Very expressive, harder to debug.
Discretionary access control lets the owner of a resource decide who else may access it, like Unix file permissions or sharing a document. Flexible, but permissions spread in ways admins cannot centrally control.
Mandatory access control enforces system-wide labels (such as clearance levels) that users cannot override. Used in military and high-security systems and in OS modules like SELinux.
Policy-based access control keeps rules in a central policy engine, written as code, and has services ask it for decisions. Open Policy Agent with Rego is the best-known example.
Relationship-based access control derives permissions from a graph of relationships: you can edit a document because you belong to the team that owns its folder. Google Zanzibar popularised it; OpenFGA and SpiceDB implement it.
API keys identify a calling application, mainly for server-to-server use, quotas and billing. Treat them like passwords: show them once, store only a hash, and let customers create, label and revoke several keys.
Scopes limit what a key or token can do (orders:read, payments:write). Issue the narrowest set needed, check them on every endpoint, and return 403 with the missing scope named.
Generate keys from a cryptographically secure source with enough entropy, add a recognisable prefix (sk_live_) so leaks are easy to scan for, and support overlapping keys so clients can rotate without downtime.
An API is only as usable as its docs. Describe it in a machine-readable spec, then generate reference pages, client SDKs, mocks and tests from that one source so they never drift apart.
OpenAPI (formerly Swagger) describes paths, parameters, schemas and auth in YAML or JSON. Swagger UI renders it as interactive docs, and generators produce servers and clients in many languages.
Postman is a client for sending requests, organising them in collections, scripting assertions and sharing environments. Collections can be published as docs or run in CI with the Postman CLI or Newman.
ReadMe is a hosted developer portal that imports an OpenAPI file and adds guides, a try-it console and per-user API logs. Handy when you want polished public docs without building a site.
Stoplight offers visual OpenAPI editing, hosted docs and mock servers, aimed at design-first teams. Its open-source Spectral linter enforces style rules on any OpenAPI file in CI.
APIs expose business logic directly, so attackers probe them with scripts rather than browsers. Security comes from layered defaults: TLS everywhere, strict input validation, per-object authorization checks, limits on everything and logs you actually review.
Broken object-level authorization (changing an ID to read someone else's data), broken authentication, mass assignment of fields, missing rate limits, SSRF and injection dominate real API breaches.
Enforce HTTPS and HSTS, validate payloads against a schema, whitelist writable fields, return only the fields a client needs, set request size limits, and keep secrets out of URLs since those end up in logs.
Fast APIs come from measuring first: find where latency goes, then cache, batch, or scale the hot path. Track tail latency rather than averages, since the slowest percentiles are what users feel.
Watch latency percentiles (p50, p95, p99), throughput, error rate and saturation of CPU, memory and connection pools. Set SLOs on these and alert on burn rate rather than single spikes.
Layer caches: HTTP caching at the client and CDN, an application cache like Redis with cache-aside or write-through, and query caching in the database. Decide invalidation and TTLs up front; stale data bugs are the usual price.
Spread requests across instances with round robin, least connections or hashing. L4 balancers route TCP; L7 balancers understand HTTP and can route by path, terminate TLS and run health checks. Stateless services make this trivial.
Beyond protecting against abuse, throttling sheds load gracefully: slow or reject low-priority traffic before the database falls over. Apply it at the gateway and keep per-tenant limits so one customer cannot starve the rest.
Monitoring tells you an endpoint got slow; profiling tells you why. Use APM traces to find slow spans such as N+1 queries, and CPU or heap profilers to find hot functions in the handler itself.
Measure latency and throughput under realistic traffic before release and compare against a baseline in CI, so regressions surface in the pull request that caused them instead of in production.
Once several services and partners talk to each other, the question shifts from single endpoints to how calls flow: synchronous or not, through a gateway or a broker, pushed or polled. These patterns trade simplicity for resilience and scale.
Synchronous calls block until the result is ready, which is simple but chains latency and failures. For slow work, accept with 202 Accepted, return a job URL to poll or a callback, and process in the background.
Services publish events (OrderPlaced) and others react without the producer knowing them. This decouples teams and absorbs spikes, at the cost of eventual consistency and harder end-to-end debugging.
A queue buffers work between producers and consumers so each side scales and fails independently. Plan for at-least-once delivery: make consumers idempotent and route poison messages to a dead-letter queue.
RabbitMQ is an AMQP broker with exchanges that route messages to queues by key or pattern, per-message acknowledgements and flexible topologies. A good fit for task queues and request routing.
Kafka is a distributed, partitioned log: messages are retained and consumers track their own offsets, so many consumers can replay the same stream. Suited to high-volume event streams and data pipelines.
Polling is simple but wasteful and laggy; webhooks push events to a client URL as they happen. Sign webhook payloads with an HMAC, retry with backoff, and expect receivers to deduplicate by event ID.
Let clients send many operations in one request, or run large imports as background jobs. Report per-item results so one bad record does not fail the whole batch, and cap batch size.
A gateway is the single entry point that handles routing, TLS, authentication, rate limits and request logging for the services behind it. Kong, Envoy, AWS API Gateway and NGINX are common choices.
Small, independently deployable services that own their data and talk over APIs or events. They let teams ship independently but add network failures, versioning and distributed tracing to every feature.
A backend-for-frontend is a thin API built for one client, such as the web app or mobile app, that aggregates downstream services and shapes responses for that screen. It keeps client logic simple and can hold tokens server-side.
Retry only transient failures and idempotent operations, with exponential backoff and jitter, and cap total attempts. Add timeouts on every call and a circuit breaker so a dead dependency fails fast instead of piling up threads.
An API is a promise to clients, so tests should verify the contract as well as the code. Combine fast unit tests for logic, integration tests against real dependencies, and contract checks so changes cannot silently break consumers.
Test validators, mappers and service logic in isolation with dependencies faked. They run in milliseconds and should cover edge cases like empty lists, boundaries and invalid input.
Start the app with a real database (often via Testcontainers) and hit endpoints over HTTP, asserting status codes, bodies and side effects. Slower, but catches wiring, serialisation and query bugs unit tests miss.
Verify user-level behaviour end to end against a deployed environment: sign up, create an order, pay. Keep the suite small and focused on critical paths because these tests are the slowest and flakiest.
Simulate expected and peak traffic with tools like k6, Gatling or Locust to find the point where latency climbs or errors start. Test against production-like data volumes, not an empty database.
Mock servers generated from an OpenAPI spec (Prism) or recorded stubs (WireMock) let frontends build before the backend exists and keep tests independent of flaky third-party services.
Consumers record the requests and responses they rely on, and the provider's CI verifies it still satisfies them. Pact is the standard tool; it catches breaking changes without full end-to-end environments.
Some data should reach the client the moment it changes: chat, live dashboards, LLM output. Real-time transports keep a connection open, which changes how you scale, load balance and authenticate.
A WebSocket upgrades an HTTP connection into a full-duplex channel for messages in both directions. Plan for reconnects, heartbeats, authentication at connect time and sticky sessions or a pub/sub backplane when scaling out.
SSE streams text/event-stream messages from server to client over plain HTTP, with automatic reconnection and Last-Event-ID resume built into EventSource. Simpler than WebSockets when data flows one way.
Send a response in chunks as it is produced (chunked transfer encoding, NDJSON, or SSE) instead of buffering it all. Clients read with the Fetch ReadableStream; proxies must not buffer, so check their settings.
APIs move through design, build, publish, version and retire stages. Announce deprecations early, signal them in responses with the Deprecation and Sunset headers, watch usage of old versions, and only remove them once traffic has moved.
APIs that touch personal, payment or health data fall under laws and industry standards. They shape what you collect, where you store it, how long you keep it, who can see it and what you must log.
The EU General Data Protection Regulation covers anyone processing EU residents' data. APIs need a lawful basis for each use, data minimisation, and endpoints or processes to export and erase a user's data on request.
The California Consumer Privacy Act, amended by the CPRA, gives California residents rights to know, delete and opt out of the sale or sharing of their data. Similar engineering needs to GDPR, different legal triggers.
The card industry's security standard for systems that store, process or transmit card data. The practical move is to never touch raw card numbers: use a provider's hosted fields or tokens to shrink your audit scope.
US rules for protected health information: encryption, access controls, audit logs and signed business associate agreements with any vendor that handles the data, including your cloud provider.
Personally identifiable information is anything that identifies a person, alone or combined: names, emails, IPs, IDs. Classify fields, mask them in logs, encrypt sensitive ones at rest and avoid putting them in URLs.
Observability lets you answer new questions about a running API without shipping code: structured logs with request IDs, metrics for rate, errors and duration, and distributed traces that follow one request across services. OpenTelemetry is the vendor-neutral way to emit all three.