REST (Representational State Transfer) is an architectural style for building web services. RESTful web services provide interoperability between computer systems on the internet by adhering to REST architectural constraints. The REST architectural style emphasizes scalability, performance, reliability and simplicity in component interactions.
What is REST?
REST stands for Representational State Transfer. It is an architectural style for building distributed systems based on hypermedia. REST is independent of any underlying protocol and is not necessarily tied to HTTP. However, most common REST implementations use HTTP as the application protocol, and this guide focuses on designing REST APIs for HTTP.
The REST architectural style defines constraints for how components in a distributed hypermedia system, such as the Web, should interact. The interaction constraints are:
- Client-server – separation of user interface concerns from data storage concerns
- Stateless – each request from the client must contain all the information necessary to service the request, session state is stored on the client
- Cacheable – responses should allow caching wherever appropriate
- Uniform interface – components interact through uniform interfaces, reducing complexity
- Layered system – components in the system cannot see beyond the component they are interacting with
- Code on demand (optional) – serve executable code such as applets or scripts for clients if needed
By applying these constraints and REST principles, RESTful systems gain desirable non-functional properties like performance, scalability, simplicity, modifiability, visibility, portability and reliability.
REST Architectural Principles
In addition to the REST architectural constraints, there are several guiding principles of RESTful API design:
- Resource identification – use logical URIs to identify resources
- Manipulation through representations – clients interact with representations of resources, not directly with resource themselves
- Self-descriptive messages – each message should contain enough information to describe how it should be processed
- Hypermedia as the engine of application state (HATEOAS) – responses contain links to transition application state
These principles encourage loosely coupled and independent components, which has benefits for scalability, flexibility and encapsulation.
Benefits of REST
Some key benefits of RESTful APIs:
- Lightweight – REST uses less bandwidth and resources than SOAP-based web services
- Faster performance – REST requires less processing power on the client side
- Scalability – REST is designed for internet-scale applications
- Flexibility – REST is not tied to any specific protocol, platform or language
- Caching – REST responses can be cached to improve performance
- Divide and conquer – allows different frontend and backend teams to work independently
- Uniform and standardized – follows consistent design principles and constraints
How to design a RESTful API
Here are some best practices for designing RESTful APIs:
Use logical resource URLs
REST APIs expose resource URLs that clients can use to interact with those resources. For example:
- /users – get a list of all users
- /users/123 – get details of user 123
- /posts/456 – get post 456
Resource URLs should be based on nouns and not actions.
Use HTTP methods meaningfully
HTTP methods (GET, POST, PUT, DELETE etc.) should be used appropriately for each action on a resource:
HTTP Method | CRUD Operation |
---|---|
GET | Read resource/s |
POST | Create a resource |
PUT | Update a resource |
DELETE | Delete a resource |
Provide filtering, sorting, pagination
REST APIs should support:
- Filtering – Fetch subsets of resources based on query criteria
- Sorting – Order collections consistently
- Pagination – Limit response size for efficiency
This improves usability for clients.
Use HTTP status codes
HTTP status codes like 200, 400, 404 etc. should be used to indicate API response status. For example:
Status Code | Description |
---|---|
200 | OK – Request succeeded |
400 | Bad request – Invalid request message |
404 | Not found – Resource does not exist |
Version your API
Versioning allows clients to continue using older API versions. Common approaches are:
- Put version in the URL: https://api.example.com/v1/users
- Custom request header: X-API-Version: 1
Provide full API documentation
REST APIs should be fully documented, including:
- Overview of API capabilities and endpoints
- Example requests and responses
- Authentication methods
- Error codes and messages
- Code samples in various languages
Support common data formats
JSON and XML are commonly used for REST API data formats. The API should allow clients to specify their preferred format.
Use HTTP authentication
Standard HTTP authentication mechanisms like Basic Auth or OAuth should be supported.
How to consume a REST API
Here are some ways that clients can consume REST APIs:
Browsers
Browsers can directly call REST API URLs and display the response. For example, entering a REST URL in the browser address bar:
https://api.example.com/users/123
Returns a JSON response:
{ "id": 123, "name": "John Doe", "email": "[email protected]" }
Browsers can also make POST/PUT requests using extensions or client-side libraries.
Command line tools
Tools like cURL allow making REST requests from the command line. For example:
$ curl https://api.example.com/users/123
Returns the JSON response for that URL.
Application code
Applications can call REST APIs by using:
- HTTP client libraries – like Java’s HttpClient or Python’s Requests
- REST client libraries – wrap HTTP libraries to make calling REST APIs easier
- Generated client SDKs – tools like Swagger Codegen can generate client SDKs for REST APIs in various languages
These libraries simplify making REST requests from application code.
Mobile/desktop apps
Native mobile or desktop apps can call REST APIs using the platform’s HTTP library:
- Android – HttpURLConnection
- iOS – URLSession
- JavaScript – Fetch API
Generated SDKs can also be used for simpler integration.
Common issues when using REST
Some common pitfalls when using REST APIs:
Not using HTTP methods properly
Using GET for everything, instead of using POST/PUT/DELETE appropriately.
Not using status codes properly
Always returning 200 OK, instead of proper status codes like 400 Bad Request or 404 Not Found.
Too granular URLs
URLs with a large number of parameters look unsightly. Use sub-resources instead.
Not supporting common HTTP features
Lack of support for caching, compression, etags leads to inefficient APIs.
Not having proper versioning
Clients break when APIs change without versioning.
Not handling errors properly
Not returning error details and codes leads to hard-to-troubleshoot issues.
Not documenting properly
Lack of comprehensive documentation hampers adoption.
Conclusion
REST provides a powerful yet lightweight approach for building scalable web services. Applying REST design principles results in an API optimized for internet-scale requirements. Standard HTTP methods allow resources to be manipulated in a simple and predictable way.
To build successful REST APIs, focus on:
- Logical identifier-based URLs
- Proper use of HTTP methods and status codes
- Support for common API features like filtering and pagination
- Consistent versioning strategy
- Thorough API documentation
- Use of standard data formats like JSON and XML
- Simple and robust error handling
A well-designed REST API allows fluid client integration across diverse platforms and scales to handle internet-level loads.