Skip to content

Rest API Design

109 companion flashcards · AI-assisted study content · Open the deck →

This deck walks you through the foundational concepts of REST API design, from the meaning behind the acronym to the practical rules for building clean, predictable web services. You'll explore what makes a resource, why statelessness matters, and how HTTP methods like GET, POST, PUT, PATCH, and DELETE each carry specific intent. The deck also covers URI design best practices, including when to use plural nouns, how to structure nested resource paths, and where query parameters fit in. Together, these cards build a clear picture of the conventions that make REST APIs consistent and easy to use.

The deck is well suited for backend developers who are designing or reviewing APIs, students learning about web services for the first time, or anyone preparing for a technical interview where REST fundamentals come up. If you're a frontend developer curious about how the endpoints you call are structured, or a technical writer documenting APIs, you'll also find these cards useful for speaking the same language as the engineers you work with.

Because the concepts here build on one another, try studying the cards in order during your first pass, then shuffle them once you feel comfortable. Pay special attention to the distinctions between similar ideas, such as PUT versus PATCH, or safe versus idempotent methods, since the deck often tests subtle differences rather than broad definitions.

Reviewing a few cards each day tends to work better than cramming everything at once, especially since REST vocabulary is easier to remember once you've started applying it to real endpoint designs. Keep a notebook handy for the terms and principles that feel new, and revisit any cards you miss before moving on to keep the foundations solid.

Foundations of REST

REST, or Representational State Transfer, is an architectural style for designing scalable web APIs that leverages the standard HTTP protocol. At its heart, a REST API exposes resources—any named, addressable entity such as a user, an order, or a document—through URIs, and represents those resources in formats like JSON. This approach turns the web's existing infrastructure into an API platform rather than inventing a new protocol, which is one reason it has become the dominant model for public and private web services.

The architectural style is defined by a set of constraints that, taken together, give REST its scalability and loose coupling. The client-server separation keeps presentation concerns on the client and data storage on the server, allowing each side to evolve independently. Statelessness requires that every request carry all the information the server needs to fulfill it; the server stores no session state between requests, which simplifies scaling because any node can handle any request. Cacheability, the layered system constraint (which permits intermediaries like load balancers and caches without the client's knowledge), the uniform interface, and the optional code-on-demand constraint round out the foundation. Together these principles push APIs toward predictability, scalability, and evolvability.

The uniform interface constraint deserves special attention because it shapes nearly every other design decision. It standardizes four things: how resources are identified with URIs, how they are manipulated through HTTP methods, the format of messages (typically JSON), and how clients discover actions through hypermedia links in the HATEOAS pattern. Because every conforming REST API uses the same vocabulary of methods and status codes, clients and tooling can be reused across services, which is a major reason the style has become so dominant.

HTTP Methods and Their Semantics

HTTP methods express the intended action on a resource, and choosing the right one is central to a clean REST design. GET retrieves a representation of a resource, POST creates a new resource or triggers a non-idempotent action, PUT replaces an entire resource with a new representation, PATCH applies partial modifications, and DELETE removes a resource. Using these standard verbs consistently means clients do not need to learn a bespoke action vocabulary for each new API they encounter, which is one of REST's biggest practical advantages.

Two related properties govern how methods behave across repeated calls. A method is safe when it does not modify server state—GET and HEAD qualify—allowing clients to prefetch responses without side effects. A method is idempotent when applying it multiple times produces the same observable result as applying it once; GET, PUT, and DELETE all share this property. Note that PUT and DELETE being idempotent does not mean they return the same response body on every call, only that the resource's state is the same after one call as after many. POST, in contrast, is intentionally non-idempotent: posting the same payload twice may create two resources, which is why external mechanisms such as idempotency keys are sometimes bolted onto POST for sensitive operations like payments.

A couple of finer-grained distinctions matter in practice. PUT replaces the whole resource with the representation provided, so clients must send every field; PATCH is the right choice when only a few fields are changing. Because PATCH operations can vary in shape, services often document a specific patching format such as JSON Patch or JSON Merge Patch so that all clients speak the same partial-update language. The OPTIONS method, although less central, has an important supporting role: browsers send it as a CORS preflight before non-simple cross-origin requests, and servers can answer OPTIONS directly to advertise the methods and headers allowed on a given resource through the Allow response header.

URI Design and Resource Modeling

Well-designed URIs make an API feel intuitive to navigate. The dominant convention is hierarchical, noun-based paths that use plural nouns for collections, such as /users/123/orders/456, where each segment narrows the scope from collection to item to related sub-collection. Plural nouns make it obvious whether you are addressing the whole set or a single member, and they read naturally when the resource itself implies plurality, as users and orders do. Following this rule consistently means clients can guess URIs from the API's domain model rather than consulting documentation.

Verb-based paths are discouraged because the HTTP method already declares the action. Saying DELETE /users/1 is more idiomatic and shorter than /deleteUser/1, and it keeps the URL focused on the resource. Query parameters, on the other hand, are the right place for everything that does not identify a specific resource: filtering, sorting, pagination, and search live in the query string so that paths remain clean and stable. For example, /users?role=admin&sort=name&page=2 keeps the resource hierarchy in the path and the slice of results in the query string. Depth should be moderated; even though nested paths like /users/123/orders/456 are valid, deeply nested hierarchies become hard to maintain and rarely reflect access patterns well—often a flatter URI plus filtering is clearer.

Versioning is the other major URI-design decision. The two common approaches are versioning through a path prefix, such as /v1/users, and versioning through the Accept request header, such as Accept: application/vnd.api.v1+json. Path versioning is the simplest to implement and to debug, since the version is visible in the URL and easy to route on. Header versioning keeps URIs clean and lets the same resource live at one address across multiple versions, which can be more flexible, but at the cost of slightly more client complexity because the version is no longer part of the path.

Status Codes and Error Handling

Status codes are the API's primary vocabulary for outcomes, and using them precisely saves clients from parsing message bodies to understand what happened. The 2xx range covers success: 200 OK is the default response for a successful GET, 201 Created is the right answer after a POST that produced a new resource (ideally with a Location header pointing to it), and 204 No Content suits successful operations with no meaningful body, such as a DELETE or a PUT with no return value. Falling back to a generic 200 in all these cases is a common anti-pattern that hides semantic information from clients and pushes them to inspect bodies to distinguish success from failure.

The 4xx range covers client errors and benefits from clear distinctions. 400 Bad Request signals that the request itself is malformed—think invalid JSON syntax or a missing required field. 404 Not Found means the addressed resource does not exist, while 422 Unprocessable Entity is reserved for semantically invalid input that parsed cleanly, such as a syntactically valid but unusable email address. Using 422 for these validation failures keeps the meaning of 400 focused on transport-level problems and gives clients a reliable way to distinguish "I cannot read what you sent" from "I read it but it does not make sense." 429 Too Many Requests is the dedicated code for rate limiting, signaling that the client has exceeded its quota and should back off; it pairs naturally with headers such as Retry-After to guide the next attempt.

Whatever the code, the response body should make the error machine-readable and consistent across the API. The de facto standard is RFC 7807's Problem Details format, a JSON structure with fields like type, title, status, detail, and instance that describes what went wrong and where. A single shared error shape lets clients write one error-handling path instead of branching per endpoint, and it makes log aggregation and support tooling far more effective.

Data Formats, Content Negotiation, and Hypermedia

JSON has become the de facto response format for REST APIs thanks to its compactness, readability, and near-universal language support. While XML and other formats are still possible, most modern APIs standardize on JSON for both request and response bodies. Rather than fix the format at design time, the more expressive approach is content negotiation: the client sends an Accept header such as Accept: application/json, and the server picks the best representation it can produce. This lets a single API serve multiple consumers with different format needs and gives a clear upgrade path if a new representation becomes desirable later, without breaking clients that pinned to the old format.

A few related techniques refine how data crosses the wire. Partial responses let the client request only the fields it needs, typically through a query parameter like ?fields=name,email, which reduces bandwidth and CPU on both ends for large resources. Compression with gzip or Brotli is also commonly applied at this layer to shrink payloads further. Hypermedia, in the form of HATEOAS, raises the abstraction by embedding links inside responses so that clients can navigate related resources and available actions dynamically—for example, a payment resource might include links to its refund, receipt, and dispute endpoints rather than forcing the client to construct URIs.

HATEOAS is one of the most powerful and least adopted aspects of REST: when implemented, it lets the server evolve URIs and add new relationships without breaking clients, because clients follow links rather than constructing paths themselves. The trade-off is response size and the complexity of describing link relations, which is why many APIs settle on returning a few stable, conventional links per resource instead of a fully hypermedia-driven interface.

Performance Patterns

Most APIs eventually have to handle large collections, expensive operations, or many small requests, and a handful of patterns cover these needs. Pagination splits a large result set into pages using query parameters—either offset-limit style with ?page=2&limit=20 or cursor-based style with an opaque token that points to the next slice. Offset pagination is intuitive and supports random access, but it grows inefficient as offsets get larger because the database still skips earlier rows; cursor pagination is faster at scale and stable in the face of new data arriving mid-scroll, but it only supports forward navigation. The right choice depends on the dataset size and access pattern, and many APIs offer both.

Beyond pagination, clients frequently need to slice collections differently: filtering parameters such as ?status=active narrow the set, sorting parameters such as ?sort=-created_at order it, and field selection such as ?fields=name,email trims each response down to the data the client asked for. Bulk and batch operations reduce round-trips when a client needs to act on many resources; a typical pattern is POST /users/batch accepting an array of operations and returning per-item results and errors so a single failure does not abort the whole call. Long-running work that cannot finish within a request is handled asynchronously: the API returns 202 Accepted with a Location header pointing at a status URI such as /tasks/123, which the client polls via GET until it reaches a terminal state of success or failure.

Caching is the other major performance lever. ETags act as resource version identifiers, and conditional requests with headers like If-None-Match or If-Modified-Since let clients avoid re-downloading unchanged representations. Cache-Control directives such as max-age and no-cache let servers control how long intermediaries and browsers may cache responses, which can dramatically reduce load for read-heavy APIs. Request bundling—a specific form of batching—combines multiple related calls into a single POST /batch to reduce chatty interactions on slow networks, trading a small amount of complexity for large latency gains on mobile clients.

Security, Authentication, and Cross-Cutting Concerns

REST APIs inherit the same threat landscape as any web service, and security must be designed in from the start. The foundation is HTTPS, which protects credentials and payloads in transit and lets clients trust the server's certificate. Beyond transport security, the OWASP API Security Top 10 highlights injection, broken authentication, and excessive data exposure as recurring issues, so input validation, output filtering, and least-privilege authorization belong in every endpoint. Authorization is best modeled around scopes attached to the authenticated identity, so each token grants only the actions it actually needs.

Several authentication mechanisms are commonly paired with REST. API keys are the simplest: a shared secret sent in a header such as X-API-Key. They are easy to issue and use, but they identify a caller only loosely and offer no built-in scoping, so they are best for service-to-service traffic with low sensitivity or for first-party clients where the key can be rotated frequently. OAuth 2.0 is the dominant framework for delegated access and third-party integrations; the resource owner grants an application a scoped access token issued by an authorization server, and the token is refreshed on a separate flow when it expires. JWTs are the most common token format used inside OAuth 2.0: compact, self-contained, signed (and optionally encrypted) structures that carry claims such as user ID, scopes, and expiration so that servers can verify identity without a session store, which fits naturally with REST's statelessness requirement.

Beyond authentication, a few cross-cutting concerns complete the picture. CORS headers tell browsers which origins, methods, and headers are allowed to call the API, which is essential when browser-based clients on different domains consume the service. Rate limiting protects availability by capping request volume per client—often exposed through headers like X-RateLimit-Remaining and X-RateLimit-Limit—and pairs naturally with the 429 response discussed earlier. Idempotency keys, sent on POST or PUT operations, ensure that retries from unreliable networks do not double-charge a payment or create duplicate records: the server remembers the key for a window of time and returns the original response on subsequent calls with the same key, making the operation effectively idempotent even when the underlying method is not.

Frequently asked questions

What does REST stand for?

REST stands for Representational State Transfer, an architectural style for designing scalable web APIs using standard HTTP protocols.

What are safe HTTP methods?

Safe methods like GET and HEAD do not modify resources; clients can prefetch them without side effects.

What response format is standard for REST APIs?

JSON is the most common format for requests and responses due to its readability, compactness, and widespread language support.

What is API authentication?

Authentication verifies client identity using methods like API keys, Basic Auth, OAuth, or JWT tokens.

What is partial response optimization?

Use fields query param (e.g., ?fields=name,email) to return only requested fields, reducing bandwidth.

What is the difference between a REST and RPC API?

REST is resource-oriented: it exposes nouns (resources) manipulated with HTTP methods. RPC is action-oriented: it exposes functions/procedures (e.g., /getUser). REST uses HTTP semantics; RPC often uses custom verbs.

What is the difference between a URI and a URL?

A URI (Uniform Resource Identifier) is a general identifier for a resource. A URL (Uniform Resource Locator) is a specific type of URI that also provides a way to locate it. In practice, all REST endpoints are URLs.

What is the difference between a media type and a format?

A media type (MIME type) like application/json identifies a data format. JSON, XML, and YAML are specific serialization formats. A media type can have parameters and vendor extensions.

What is a refresh token in OAuth 2.0?

A refresh token is a long-lived credential used to obtain new access tokens when the short-lived access token expires. It is kept server-side and exchanged via the token endpoint, reducing exposure of access tokens.

What is the difference between polling and webhooks?

Polling repeatedly requests an endpoint on a schedule to check for changes (simpler, more traffic). Webhooks push events to the client when they occur (efficient, but requires a reachable endpoint and signature verification).

Drill this topic

109 flashcards on Rest API Design — free, no signup needed to start.

Study Rest API Design flashcards

LearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.