REST (Representational State Transfer) is an architectural design principle for building distributed hypermedia systems. REST defines a set of constraints for creating web services that are simple, scalable, and maintainable. By leveraging HTTP protocol semantics and designing APIs around resources and standard HTTP methods, REST enables the construction of intuitive and interoperable web services that have become the de facto standard for modern web development.
How to Pronounce REST API
rest ay-pee-eye /rɛst ˌeɪ.piː.ˈaɪ/
rest (/rɛst/)
Definition and Core Concepts
REST was proposed in 2000 by Roy Fielding in his doctoral dissertation at the University of California, Irvine. By analyzing the architectural principles underlying the success of the World Wide Web, Fielding identified a set of design constraints that explain why the Web has become so scalable and successful. REST is not a protocol but rather an architectural style—a set of guidelines for designing networked systems.
REST is defined by six architectural constraints, five of which are mandatory:
- Client-Server Architecture: The system is composed of clients and servers. Clients and servers evolve independently as long as the interface between them remains unchanged.
- Statelessness: Each request from client to server must contain all information needed to understand and process the request. The server must not retain client session state. This improves visibility, reliability, and scalability.
- Cacheability: Responses should be defined as cacheable or non-cacheable to prevent clients from reusing stale or inappropriate data. Well-managed caching partially or completely eliminates some interactions, improving network efficiency.
- Uniform Interface: A uniform interface simplifies and decouples the architecture, enabling each part to evolve independently. The uniform interface is achieved through resource identification, resource manipulation through representations, self-descriptive messages, and HATEOAS (Hypermedia As The Engine Of Application State).
- Layered System: Clients cannot ordinarily tell whether they are connected directly to the end server or to an intermediary. Layered systems can be composed of hierarchical layers in which each layer does not “see” beyond the immediate layer.
- Code on Demand (Optional): REST allows client functionality to be extended by downloading and executing applets or scripts. This is the only optional constraint.
An application that adheres to REST architectural constraints is called “RESTful.”
HTTP Methods and RESTful Operations
REST APIs utilize standard HTTP methods to implement Create, Read, Update, and Delete (CRUD) operations on resources:
- GET: Retrieves a representation of a resource. GET is a safe method—it does not modify server state and can be called multiple times safely.
- POST: Creates a new resource or triggers an action. The request body contains the data for the new resource.
- PUT: Replaces an entire resource with a new representation. The client must provide the complete resource definition.
- PATCH: Applies partial modifications to a resource. Only changed fields need to be provided.
- DELETE: Removes a resource from the server.
- HEAD: Similar to GET but requests only the headers without the response body.
- OPTIONS: Describes communication options available for a resource.
Each method has distinct semantics: GET and HEAD are safe (read-only), while GET, HEAD, and DELETE are idempotent (repeated requests produce the same result).
Code Examples
JavaScript Fetch API – GET Request:
// Fetch user information
fetch('https://api.example.com/users/123')
.then(response => response.json())
.then(data => console.log('User:', data))
.catch(error => console.error('Error:', error));
JavaScript Fetch API – POST Request:
// Create a new user
const newUser = {
name: 'John Doe',
email: 'john@example.com',
role: 'developer'
};
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log('Created user:', data))
.catch(error => console.error('Error:', error));
JavaScript Fetch API – PUT Request:
// Update an entire user resource
const updatedUser = {
name: 'Jane Doe',
email: 'jane@example.com',
role: 'manager'
};
fetch('https://api.example.com/users/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updatedUser)
})
.then(response => response.json())
.then(data => console.log('Updated user:', data));
JavaScript Fetch API – PATCH Request:
// Partially update a user (change only email)
fetch('https://api.example.com/users/123', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: 'newemail@example.com' })
})
.then(response => response.json())
.then(data => console.log('Updated user:', data));
cURL Examples:
# GET request
curl https://api.example.com/users/123
# POST request
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com"}'
# PUT request
curl -X PUT https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"name":"Jane Doe","email":"jane@example.com"}'
# PATCH request
curl -X PATCH https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"email":"newemail@example.com"}'
# DELETE request
curl -X DELETE https://api.example.com/users/123
HATEOAS (Hypermedia)
HATEOAS, an acronym for “Hypermedia As The Engine Of Application State,” is a core REST principle. HATEOAS means that responses include hyperlinks to possible next actions, allowing clients to discover available operations dynamically rather than hardcoding endpoint URLs.
HATEOAS Example Response:
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2026-01-15T10:30:00Z",
"_links": {
"self": {
"href": "https://api.example.com/users/123",
"method": "GET"
},
"all_users": {
"href": "https://api.example.com/users",
"method": "GET"
},
"update": {
"href": "https://api.example.com/users/123",
"method": "PUT"
},
"delete": {
"href": "https://api.example.com/users/123",
"method": "DELETE"
},
"posts": {
"href": "https://api.example.com/users/123/posts",
"method": "GET"
}
}
}
Content Negotiation
REST APIs support multiple representation formats through content negotiation. Clients specify their preferred format using the Accept header, and servers respond with data in the requested format. Common formats include JSON, XML, YAML, and Protocol Buffers.
// Request JSON format
fetch('https://api.example.com/users/123', {
headers: {
'Accept': 'application/json'
}
});
// Request XML format
fetch('https://api.example.com/users/123', {
headers: {
'Accept': 'application/xml'
}
});
HTTP Status Codes
REST APIs communicate operation outcomes through standardized HTTP status codes:
- 2xx Success:
- 200 OK: Request succeeded
- 201 Created: Resource created successfully
- 204 No Content: Request succeeded but no content to return
- 3xx Redirection:
- 301 Moved Permanently: Resource moved permanently
- 304 Not Modified: Resource has not changed since last request
- 4xx Client Error:
- 400 Bad Request: Invalid request syntax
- 401 Unauthorized: Authentication required
- 403 Forbidden: Authenticated but not authorized
- 404 Not Found: Resource does not exist
- 409 Conflict: Request conflicts with current state
- 422 Unprocessable Entity: Validation failed
- 5xx Server Error:
- 500 Internal Server Error: Server-side error
- 503 Service Unavailable: Server temporarily unavailable
API Versioning Strategies
As APIs evolve, versioning ensures backward compatibility with existing clients. Common versioning approaches include:
- URL Path Versioning: Include version in the URL path (e.g.,
/api/v1/users,/api/v2/users). Most explicit and easiest to implement. - Query Parameter Versioning: Specify version as a query parameter (e.g.,
/api/users?version=1). Less obvious but cleaner URLs. - Header Versioning: Specify version in request headers (e.g.,
Accept: application/vnd.company.v1+json). Keeps URLs clean but requires header inspection. - Semantic Versioning: Use major.minor.patch format (e.g., v1.2.3) to indicate breaking changes, features, and fixes.
REST vs SOAP vs GraphQL: Comparison
Different approaches exist for building web services. Here’s how REST compares with SOAP and GraphQL:
| Characteristic | REST | SOAP | GraphQL |
|---|---|---|---|
| Type | Architectural style | Protocol specification | Query language & runtime |
| Protocol | HTTP (leverages methods) | XML-RPC based | HTTP (primarily POST) |
| Data Format | JSON (standard), XML, YAML | XML only | JSON |
| Learning Curve | Low (simple & intuitive) | High (complex specification) | Moderate (new paradigm) |
| Overfetching | Common | Minimal | Eliminated (query-specific) |
| Underfetching | Common | Minimal | Eliminated (single request) |
| Caching | Excellent (HTTP cache) | Difficult | Challenging (POST-based) |
| Performance | High (minimal overhead) | Lower (XML parsing) | Moderate (query parsing) |
| Adoption | Extremely high (industry standard) | Low (legacy systems) | Growing (modern applications) |
| Real-time Support | Limited (polling required) | Limited | Good (subscriptions) |
Common Misconceptions
Misconception 1: “REST Requires JSON”
The REST architectural constraints do not mandate any specific data format. JSON has become popular due to its simplicity and widespread tooling support, but XML, YAML, Protocol Buffers, and other formats are equally valid in REST architectures.
Misconception 2: “All HTTP APIs Are REST”
Many APIs labeled as “REST” actually violate core REST constraints. RPC-style APIs using HTTP (e.g., `/api/getUserById`, `/api/createPost`) are not truly RESTful. True REST requires resource-oriented design with proper use of HTTP methods and status codes.
Misconception 3: “REST Is Outdated”
REST is an architectural principle, not a technology trend subject to replacement. While GraphQL and gRPC serve specific use cases, REST remains the dominant standard for web API design in 2026 and continues to be the foundation of most modern web services.
Misconception 4: “REST Cannot Handle Real-time Communication”
REST itself doesn’t prohibit real-time communication—it’s just request-response oriented. WebSocket, Server-Sent Events (SSE), and polling can complement REST APIs for real-time needs.
Misconception 5: “REST Always Provides Better Performance”
REST’s stateless nature and HTTP caching provide good performance for many scenarios, but GraphQL can be more efficient for specific use cases with complex data requirements and overfetching concerns.
REST API Design Best Practices
- Resource-Oriented Design: Design around nouns (resources) rather than verbs. Use `/users/123` instead of `/getUser/123`.
- Proper HTTP Methods: Use GET for retrieval, POST for creation, PUT/PATCH for updates, DELETE for removal. Don’t overload GET with side effects.
- Meaningful HTTP Status Codes: Return semantically correct status codes (200 for success, 201 for creation, 400 for bad request, 404 for not found, 500 for server error).
- Consistent URL Structure: Use consistent naming conventions, plural nouns for collections (`/users`, `/posts`), and logical hierarchies (`/users/123/posts`).
- Stateless Servers: Each request should be independent and contain all information needed for processing.
- Comprehensive Documentation: Use OpenAPI (Swagger), GraphQL IDL, or similar tools to provide complete API documentation.
- Security: Implement authentication (API keys, OAuth 2.0, JWT), use HTTPS, enforce rate limiting, and validate all inputs.
- Error Handling: Return detailed error messages with appropriate status codes and error codes for client-side handling.
- Pagination: Implement pagination for large result sets using limit/offset or cursor-based approaches.
- Filtering and Sorting: Support query parameters for filtering and sorting to reduce unnecessary data transfer.
Authentication and Security
REST APIs require proper authentication and authorization mechanisms:
- API Key Authentication: Simple but limited. Suitable for public APIs or internal services. Keys should be transmitted via HTTPS only.
- OAuth 2.0: Industry standard for delegated authorization. Enables third-party applications to access user data without sharing passwords.
- JWT (JSON Web Tokens): Self-contained tokens carrying user claims. Stateless and scalable, ideal for microservices architectures.
- mTLS (Mutual TLS): Certificate-based authentication for service-to-service communication. Provides strong security.
- Rate Limiting: Prevent abuse and ensure fair resource allocation by limiting request rates per client.
FAQ (Frequently Asked Questions)
Q1: What is the difference between REST and RESTful?
A: REST is the architectural style defined by Fielding’s six constraints. RESTful describes an API or application that adheres to REST principles. Not all HTTP APIs are RESTful—only those following REST constraints.
Q2: Should I use PUT or PATCH for updates?
A: Use PUT when replacing an entire resource (client must provide complete representation). Use PATCH for partial updates (client provides only changed fields). PATCH is more flexible and bandwidth-efficient for partial modifications.
Q3: How should I structure API endpoints?
A: Use resource-oriented design with clear hierarchies: `/api/v1/users/123/posts/456`. Avoid RPC-style endpoints like `/api/getUserPosts`. Keep URLs descriptive but concise.
Q4: Is JSON required for REST APIs?
A: No. While JSON is ubiquitous due to JavaScript integration and simplicity, REST supports multiple formats. Use content negotiation to support JSON, XML, and other formats based on client needs.
Q5: How do I handle API versioning?
A: Choose one consistent approach (URL path, query parameter, or header versioning) and stick with it. URL path versioning (`/api/v1/`) is most common and explicit. Plan for graceful deprecation of old versions.
Q6: What’s the difference between status codes 400 and 422?
A: 400 Bad Request indicates malformed syntax (e.g., invalid JSON). 422 Unprocessable Entity indicates valid syntax but semantic errors (e.g., validation failure on a field).
Q7: How should errors be formatted in responses?
A: Provide consistent error responses with status code, error code/identifier, descriptive message, and optionally additional details. Clients should parse these programmatically, not rely on message text.
Q8: Should I use pagination for all endpoints?
A: Yes, implement pagination for endpoints that return collections. Even if your dataset is small now, pagination prevents future scalability issues. Use limit/offset or cursor-based approaches.
Practical Example: Building a Blog API
Resource Structure:
// Collections
GET /api/v1/posts - List all posts
GET /api/v1/users - List all users
// Individual resources
GET /api/v1/posts/123 - Get specific post
GET /api/v1/users/456 - Get specific user
// Nested resources
GET /api/v1/users/456/posts - Get user's posts
GET /api/v1/posts/123/comments - Get post's comments
// Creating resources
POST /api/v1/posts - Create new post
POST /api/v1/posts/123/comments - Create comment on post
// Updating resources
PUT /api/v1/posts/123 - Replace entire post
PATCH /api/v1/posts/123 - Partially update post
// Deleting resources
DELETE /api/v1/posts/123 - Delete post
DELETE /api/v1/posts/123/comments/789 - Delete specific comment
Tools and Frameworks for REST APIs
- API Documentation: OpenAPI/Swagger, API Blueprint, RAML
- Backend Frameworks: Express.js, Django Rest Framework, Spring Boot, Ruby on Rails, FastAPI
- Client Libraries: Axios, Fetch API, Requests (Python), OkHttp (Java)
- Testing Tools: Postman, Insomnia, REST Client (VS Code)
- Monitoring: API Gateway solutions, Datadog, New Relic, Prometheus
REST in Microservices Architecture
REST is the dominant communication protocol in microservices architectures. Services expose well-defined REST APIs, enabling loose coupling and independent deployment. However, for internal service-to-service communication with high throughput requirements, alternatives like gRPC may be preferable.
References and Further Reading
- Roy Fielding (2000): “Architectural Styles and the Design of Network-based Software Architectures” – Doctoral dissertation
- RFC 7230-7235: Hypertext Transfer Protocol (HTTP/1.1) Specifications
- RFC 6749: The OAuth 2.0 Authorization Framework
- OpenAPI Specification: https://spec.openapis.org
- Richardson, Leonard & Ruby, Sam (2007): “RESTful Web Services”
- Fielding, Roy & Taylor, Richard (2000): “Principled Design of the Modern Web Architecture”
- Related concepts: HTTP, API, JSON, XML, Microservices, gRPC, GraphQL, WebSocket, OAuth 2.0
Summary
REST (Representational State Transfer) is an architectural design principle proposed by Roy Fielding in 2000 for building distributed hypermedia systems. It defines six constraints—client-server architecture, statelessness, cacheability, uniform interface, layered systems, and optional code on demand—that promote scalability, simplicity, and reliability in web services.
REST APIs leverage HTTP semantics by using standard methods (GET, POST, PUT, PATCH, DELETE) to perform operations on resources identified by URLs. While JSON has become the de facto standard representation format, REST does not mandate any specific format. JSON’s dominance results from its simplicity and JavaScript integration, but XML, YAML, and other formats are equally valid.
The core advantages of REST include simplicity, excellent HTTP caching support, stateless server design enabling horizontal scalability, natural alignment with HTTP semantics, and widespread developer familiarity. Challenges include overfetching and underfetching of data, limited real-time support, and potential chattiness for complex data requirements.
REST remains the dominant standard for web API design, forming the foundation of most modern web services, microservices architectures, and cloud platforms. While alternative paradigms like GraphQL and gRPC address specific use cases, REST’s elegant design principles and proven track record ensure its continued relevance in 2026 and beyond. Understanding REST principles is essential for any software architect or developer building networked systems.
📖 Japanese version available / 日本語版も利用可能
日本語版を読む
















Leave a Reply