REST API Fundamentals: Designing Efficient and Understandable APIs
In the modern software development world, communication between applications is key. REST API (Representational State Transfer Application Programming Interface) plays a vital role in connecting different systems. This article will dive into the fundamentals of REST API, how to design an effective API, and its limitations.
What is REST?
REST is an architectural style for building web services. It is not a specific protocol, but rather a set of constraints that web services must adhere to in order to be considered "RESTful". This allows systems to interact with each other in a consistent and easy way.
The main principles of REST
REST APIs follow six key architectural principles:
- Client-Server: Client and server operate independently of each other. Client sends request, server processes and returns response. Client does not need to know the server's processing logic and server does not need to know the client's user interface.
- Stateless: Each request from the client to the server must contain all the information necessary for the server to understand and process the request. The server does not store any state of the client between requests. This increases the scalability of the system. For example, each request must have full authentication information, the server will authenticate based on that information and does not need to remember whether the client is logged in or not. Learn more aboutstateless architecture .
- Cacheable: Responses from the server can be marked as cacheable or non-cacheable. Clients can cache cacheable responses for use in subsequent requests, reducing server load and improving performance.
- Layered System: The architecture may include multiple intermediate layers (e.g. proxies, load balancers) that the client does not need to know about. For example, a request may go through a reverse proxy or API Gateway before reaching the actual server.
- Code on Demand (Optional): The server can extend the functionality of the client by sending executable code (e.g. Java applets, JavaScript). This principle is rarely used in practice.
- Uniform Interface: This is the most important principle, ensuring consistency and understanding in communication between client and server. Uniform Interface includes 4 smaller constraints:
- Resource Identification: Each resource must be uniquely identified by a URI (Uniform Resource Identifier).
- Resource Manipulation through Representations: Clients manipulate resources by sending representations (e.g. JSON, XML) of the resource.
- Self-descriptive Messages: Each message (request or response) must contain enough information for the client or server to understand and process it. For example, the message must have a Content-Type header to specify the format of the data.
- Hypermedia as the Engine of Application State (HATEOAS): The server returns links in the response to guide the client about possible next actions. This principle helps the client explore the API dynamically.
Important Components of REST API
To better understand REST API, we need to get familiar with the following components:
- Resources: Resources are objects or concepts that the API provides. For example: users, products, posts. Each resource is identified by a unique URI.
- Endpoints: An endpoint is a specific URI that a client uses to access a resource. For example: /users (get a list of users), /users/123 (get information about the user with ID 123).
- HTTP Verbs: HTTP verbs specify the action a client wants to perform on a resource. Common methods include:
- GET : Get resource information.
- POST : Create a new resource.
- PUT : Update all information of a resource.
- PATCH : Updates a portion of a resource's information.
- DELETE : Delete a resource.
- Statelessness: As mentioned above, the server does not store any client state between requests.
- JSON (JavaScript Object Notation): JSON is a popular data format used to exchange data between clients and servers. It is easy to read, easy to parse, and widely supported by many programming languages.
Design a simple REST API
Let's look at an example of how to design a REST API for user management.
Endpoints
- GET /users : Get a list of all users.
- POST /users : Create a new user.
- GET /users/{id} : Get information of user with ID {id} .
- PUT /users/{id} : Update all information of user with ID {id} .
- PATCH /users/{id} : Updates a part of the information of the user whose ID is {id} .
- DELETE /users/{id} : Delete the user with ID {id} .
Example of request and response
GET /users/123
Request:
GET /users/123 HTTP/1.1 Accept: application/json
Response:
HTTP/1.1 200 OK Content-Type: application/json { "id": 123, "name": "Alice", "email": "alice@example.com" }
POST /users
Request:
POST /users HTTP/1.1 Content-Type: application/json { "name": "Bob", "email": "bob@example.com" }
Response:
HTTP/1.1 201 Created Content-Type: application/json Location: /users/456 { "id": 456, "name": "Bob", "email": "bob@example.com" }
Note: HTTP status code 201 Created is used to signal that a new resource has been successfully created. Location header contains the URI of the newly created resource.
Limitations of REST API
Although REST API is a popular architecture, it also has some limitations:
- Over-fetching: The client may receive more data than necessary. For example, when fetching user information, the client may receive all fields (name, email, address, etc.) even though only the name and email should be displayed.
- Under-fetching: The client may need to make multiple requests to fetch all the data it needs. For example, to display an article's information and author's information, the client may need to make one request to fetch the article's information and another request to fetch the author's information.
- Multiple Round Trips: Under-fetching results in the client needing to make multiple round trips to the server, reducing performance.
These limitations have led to the emergence of other API architectures such as GraphQL and gRPC.
REST API and GraphQL/gRPC
GraphQL allows the client to specify exactly what data it needs, solving the over-fetching and under-fetching problems of REST APIs. gRPC uses Protocol Buffers to exchange data, allowing for more efficient data transfer than REST APIs (especially in real-time applications).
For example, Netflix uses Kafka for streaming logs. Slack uses WebSockets for chat.
Conclude
REST API is a powerful and flexible architecture for building web services. Understanding the fundamentals of REST API is important for any software developer. However, it is important to be aware of the limitations of REST API and consider alternatives such as GraphQL or gRPC when appropriate for your application requirements.
Frequently Asked Interview Questions
- Explain the basic principles of REST.
- What is the difference between PUT and PATCH ? When should you use which method?
- Why is statelessness important in REST API?
- What would you do to improve the performance of a REST API? (Suggestions: caching, pagination, compression)
- What are the limitations of REST API? What alternatives can you suggest?