REST, or Representational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. REST-compliant systems, often called RESTful systems, use HTTP requests to GET, PUT, POST and DELETE data.
What is REST?
REST is a set of constraints and principles, originally defined by Roy Fielding in 2000, that outline how web standards, such as HTTP and URIs, are supposed to be used to design web services. Some key principles of REST include:
- Stateless – No client information is stored on the server between requests. Session state is held on the client.
- Cacheable – REST responses must define if they are cacheable or not.
- Client-server separation – Clients and servers can evolve independently.
- Uniform interface – Resources requested are identifiable through a single URI.
- Layered system – Client cannot tell if it is connected directly to end server or intermediary.
By following these constraints and principles, REST aims to create a web service API ecosystem that emphasizes reliability, fast performance, scalability, and simplicity in connecting systems together. APIs that follow the REST principles are called RESTful APIs.
REST APIs
A REST API breaks down a transaction to create a series of small modules. Each module addresses a specific underlying part of the transaction. This modularity provides developers with a lot of flexibility but can be challenging to design. Some key aspects of REST APIs include:
- Resources – REST APIs operate on resources. A resource can be any object the API can provide information about or perform actions on. Each resource has a unique identifier, usually a URL.
- HTTP methods – APIs use common HTTP methods to indicate the desired action on a resource. GET, POST, PUT, PATCH and DELETE are commonly used.
- Stateless – API calls contain all information required to complete the request. No session data is stored between calls.
- Endpoints – Endpoints (URLs) define the structure of the API and how to access resources. Good endpoint design is central to API usability.
For example, if an API provides data about dogs, some endpoints might be:
- GET https://api.example.com/v1/dogs – Retrieve list of all dogs
- GET https://api.example.com/v1/dogs/{id} – Get a specific dog by unique ID
- POST https://api.example.com/v1/dogs – Create a new dog
The endpoints define the resources offered (dogs), the actions allowed on them (GET, POST) and how they are identified (using IDs).
Benefits of REST APIs
There are many benefits to using REST APIs:
- Simplicity – REST uses simpler architecture, minimizing processing needs.
- Flexibility – Services can be written in any language and client can use any tool or library.
- Scalability – Stateless interactions mean scaling horizontally is easier.
- Separation – Clear separation between client and server reduces dependencies.
- Reliability – REST is built upon HTTP which defines error handling already.
The simplicity, flexibility and scalability of REST has helped it become the dominant architectural style for APIs. Large web service providers like Google, Amazon and eBay all offer public REST APIs for interacting with their services.
Example REST API
Here is an example REST API that allows managing a list of “to do” items. It demonstrates some common design practices of REST APIs.
HTTP Methods
The API uses standard HTTP methods to perform actions:
- GET /items – Get a list of all items
- POST /items – Create a new item
- GET /items/{id} – Get an item by ID
- PUT /items/{id} – Update an item by ID
- DELETE /items/{id} – Delete an item by ID
Resources
“Items” are the resource here. All actions are performed on the collection of items or individual items.
Identifiers
Items are identified by a simple numeric ID like 5 or 22. The IDs are included in the endpoint URLs.
Messages
Requests and responses have standard definition formats. For example, GET /items returns a JSON list of items:
[ { "id": 1, "name": "Create REST API", "completed": false }, { "id": 2, "name": "Learn about REST", "completed": true } ]
While POST /items expects a JSON payload like:
{ "name": "New task" }
With responses returning status codes like 200, 401 or 404 to indicate outcomes.
Stateless
No client session data is stored on the server. Session state is held entirely on the client.
REST vs RESTful
REST (Representational State Transfer) is the architectural style of an API using HTTP methods to access resources through endpoints. RESTful describes APIs designed with REST principles and constraints in mind. So an API can be RESTful, meaning it adheres to REST principles. But there is no single official REST standard, so RESTful APIs have flexibility in design.
REST vs HTTP
REST APIs rely heavily on HTTP methods to perform actions on resources. But REST and HTTP are not the same thing:
- HTTP is a protocol for sending requests and responses between clients and servers.
- REST is an architectural style for APIs using HTTP methods.
So HTTP is one of the standards that REST APIs utilize. But using HTTP alone does not make an API RESTful. REST also specifies constraints around stateless design, caching, uniform interfaces, etc.
REST vs JSON API
JSON API is a specification for structuring API response formats using JSON data. It outlines standards for resource objects, pagination, HTTP status codes and more. REST is an architectural style for API design. The two are complementary:
- REST defines principles for API architecture.
- JSON API defines standards for API response formatting.
So an API could be both RESTful by design while also conforming to the JSON API formatting standards.
REST vs SOAP
REST | SOAP |
---|---|
Uses simple HTTP methods like GET, POST, PUT, DELETE | Has its own XML-based protocol, SOAP |
Response in easy format like JSON, XML | Response always in XML format |
Stateless, no client context on server | Stateful, client context stored on server |
Less bulky, more lightweight | More bulky due to XML schema |
More flexible and easy to use | More rigid contract-based approach |
In summary, REST aims to leverage simpler HTTP constructs whereas SOAP is an XML-based messaging protocol.
REST Operation Examples
Here are some examples of common operations in a REST API:
GET Resource
Retrieve a resource (or collection of resources):
GET /items/1
POST Resource
Create a new resource. The request body contains the resource details:
POST /items { "name": "New item" }
PUT Resource
Update an existing resource. The request body contains updated info:
PUT /items/1 { "name": "Updated name" }
PATCH Resource
Partially update a resource. Request body contains partial changes only:
PATCH /items/1 { "completed": true }
DELETE Resource
Delete a resource:
DELETE /items/1
Common Status Codes
REST APIs use HTTP status codes to indicate API response status:
Status Code | Meaning |
---|---|
200 OK | Success |
201 Created | Resource created |
204 No Content | Request succeeded, no content returned |
400 Bad Request | Malformed request |
401 Unauthorized | Authentication required |
403 Forbidden | Access to resource refused |
404 Not Found | Resource does not exist |
500 Internal Server Error | Server error |
Versioning REST APIs
There are a few common techniques used to version REST APIs:
URI Versioning
The URI path contains the API version:
https://api.example.com/v1/items https://api.example.com/v2/items
Query Parameter Versioning
API version is specified as a query parameter:
https://api.example.com/items?version=1 https://api.example.com/items?version=2
Custom Header Versioning
API version is sent in a custom header:
GET /items HTTP/1.1 X-API-Version: 1 GET /items HTTP/1.1 X-API-Version: 2
Media Type Versioning
API version is specified in the Accept header:
Accept: application/vnd.example.v1+json Accept: application/vnd.example.v2+json
Overall, URI versioning is the most common and straightforward approach to API versioning.
Documentation with OpenAPI
OpenAPI (formerly Swagger) is a specification for defining REST APIs in a language-agnostic interface description. It provides a standard format for documentation that can be used to:
- Describe API resources, endpoints, operations, parameters, etc.
- Generate interactive API documentation
- Auto-generate client SDKs
- Test APIs
OpenAPI docs are YAML or JSON files that fully outline the API structure. Many tools integrate with OpenAPI to streamline API development workflows.
REST API Security
Some key considerations around REST API security include:
HTTPS
HTTPS should be used to secure all communication and prevent tampering.
Authentication
Use API keys, OAuth, JWT tokens or some authentication mechanism to verify app identity.
Access Control
Implement access policies restricting resources to authorized apps/users.
Input Validation
Validate all input on the server side for correctness.
Rate Limiting
Enforce request rate limits to prevent brute force attacks.
Audit Logs
Log request IDs, source IPs, etc. to identify anomalies.
Conclusion
REST is an extremely popular architectural style for building scalable, lightweight and maintainable web services. Leveraging HTTP methods to access named resources and standard status codes, REST APIs provide an easy way to integrate systems. Designing APIs with REST principles in mind leads to services that are simple, flexible and reliable.