Complete REST API Design
This video presents an in-depth explanation of REST API design with a focus on creating scalable, standardized, and maintainable backends. It covers foundational concepts, HTTP method semantics, URL and resource naming conventions, state transfer theory, CRUD operations, pagination, filtering, sorting, and handling custom actions. The guide is practical with real-world workflow examples for API design in a project management platform context.
1. Introduction to REST API Design
API design is fundamental for backend engineers, with REST APIs being one of the most widely used standards. Despite long-established conventions, common questions persist about URI naming, HTTP methods, status codes, and handling non-standard actions.
- REST API design helps backend teams avoid confusion and focus on business logic by adhering to well-established practices.
- Modern frontend ecosystems have shifted from multi-page applications (MPAs) to single-page applications (SPAs), influencing how APIs are consumed.
- The goal is to standardize design, payloads, and documentation to improve developer experience on both client and server sides.
2. Historical Context and REST Architectural Principles
Understanding REST requires historical perspective on the development of the web by Tim Berners-Lee and the scalability challenges addressed by Roy Fielding via REST constraints.
Key Historical Developments
REST Architecture Constraints (Roy Fielding)
- Client-Server Separation: UI and business logic are separated.
- Uniform Interface: Standardized communication via resources and representations (Uniform Resource Identifiers, standard HTTP methods).
- Layered System: Multiple layers with possible intermediaries like load balancers, improving scalability.
- Cacheability: Server responses are explicitly flagged as cacheable or non-cacheable.
- Statelessness: Each request includes all necessary information; servers do not retain client state, aiding load balancing.
- Code on Demand (Optional): Servers can provide executable code to clients (e.g., JavaScript) temporarily.
3. Meaning Behind Representational State Transfer (REST)
- Representational: Resources (data objects) are conveyed in various formats like JSON, XML, or HTML depending on client-server context.
- State: A resource’s current attributes (e.g., user’s name, creation date) which can change over time.
- Transfer: Movement of these resource representations via HTTP methods (GET, POST, PUT, PATCH, DELETE) between client and server.
4. RESTful URLs and Resource Naming
- Full URL components include: scheme (
https), subdomain (api.), domain, versioning (v1), resource path, query parameters, and fragments. - Resource names in URLs should always be in plural form even for single-item access (e.g.,
/books/123not/book/123). - Use lowercase letters and hyphens (
-) to separate words in URL slugs—avoid spaces and underscores. - The forward slash
/in URLs represents hierarchy (e.g.,/books/123means resource collectionbooksthen a singlebookidentified by123).
5. Idempotency and HTTP Methods
Idempotency is crucial: performing the same operation multiple times must result in the same effect as a single execution.
- GET, PUT, PATCH, DELETE are idempotent. Multiple calls yield the same result after the first.
- POST is non-idempotent. Each request may trigger new changes (resource creations, custom actions).
6. Designing API Endpoints: Project Management Platform Example
Resources identified from wireframes and requirements represent nouns such as organizations, projects, tasks, and users.
Workflow for API Design
- Identify resources (nouns) from user stories or UI wireframes.
- Design database schemas based on these resources.
- Design API endpoints reflecting CRUD operations and additional custom actions.
API URL Structure Examples
HTTP Status Codes and Responses
7. List API Features: Pagination, Sorting, and Filtering
To handle large datasets efficiently and provide better client experiences, RESTful list APIs support:
Pagination
- Limits the number of returned items per request.
- Parameters:
limit(number of items per page),page(current page number). - Server provides metadata for UI:
total: total number of resources.page: current page number.totalPages: total pages available.
Sorting
- Parameters:
sortBy: the field name to sort by (e.g., name, createdAt).sortOrder:asc(ascending) ordesc(descending).
- Servers should implement default sorting (usually by
createdAt DESC) if none provided to ensure consistent results.
Filtering
- Clients can filter results based on field values (e.g., status).
- Implemented as query parameters with field names.
These features combined help optimize data delivery, reducing payloads and bandwidth, and improve frontend user experience.
8. Partial Updates (PATCH) Versus Full Replacement (PUT)
- Use PATCH for partial updates with a subset of the resource fields.
- Use PUT to entirely replace the resource representation.
- PATCH is preferable in modern API designs for flexibility, aligning with SPA and JSON use-cases.
- Maintain semantic correctness to avoid confusion for API consumers.
9. Custom Actions Using POST
- POST is the open-ended method for actions outside CRUD semantics, e.g., sending emails, archiving organizations, cloning projects.
- These endpoints follow hierarchical URI patterns ending with action names, e.g.,
/organizations/{id}/archive. - POST-based custom actions can return 200 OK if no resource created or 201 Created if a new resource is generated during the action.
10. Consistency and Standards in API Design
- Maintain plural resource names across all endpoints.
- Use consistent JSON field naming conventions (camelCase preferred).
- Apply consistent parameter names and response structures across all resource APIs.
- Avoid arbitrary idiosyncratic changes between different resource APIs to reduce confusion and integration errors.
- Always build APIs starting from understanding user interaction flows, linking UI/UX requirements to resource and action definitions.
Summary Table of REST API Best Practices
This comprehensive approach ensures scalable, predictable, and easy-to-use REST APIs tailored for modern backend development and frontend consumption.