DEV Community

PeterMilovcik
PeterMilovcik

Posted on

REST API - Best Practices

Basics of HTTP applied to REST

  1. HTTP Methods: REST APIs use HTTP methods (verbs) such as GET, POST, PUT, DELETE, and PATCH to perform operations on the resource.
  2. Status Codes: REST APIs use standard HTTP status codes to indicate the success or failure of an API call.
  3. URIs: REST APIs use Uniform Resource Identifiers (URIs) to identify resources.
  4. Headers: REST APIs use HTTP headers to provide additional context for the request or response.
  5. Payloads: REST APIs use payloads to send data in the request or response body. Payloads can be in the form of JSON, XML, or other formats.
  6. Endpoint is the combination of a verb and an URI, e.g. GET: /books/
  7. Endpoint can be interpreted as an action on a resource.
    • For example, POST: /books/ may mean "Create a new book".
  8. At a high-level, verbs map to CRUD operations
    • GET - Read
    • POST - Create
    • PUT and PATCH - Update
    • DELETE - Delete
  9. The status of a response is indicated by its status code, which is one of the following:
    • "1xx" - information
    • "2xx" - success
    • "3xx" - redirection
    • "4xx" - client errors
    • "5xx" - server errors

Why should REST API accept and respond with JSON?

REST APIs should accept and respond with JSON because it is a lightweight, language-independent data format that is easy to read and write. JSON is also widely supported by many programming languages, making it a convenient choice for exchanging data between different systems. Additionally, JSON is self-describing, meaning that it is easy to understand the structure of the data without having to look up any documentation. It is standard procedure for APIs to accept JSON queries as the payload and to return responses in JSON format. Returning a body with a JSON-formatted string inside of it is insufficient. The developer must also specify the Content-Type header. It must have the value application/json set. It is essential for programmatic clients because some rely on this header to correctly decode the response.

In short, JSON is a popular and convenient choice for exchanging data between systems, and REST APIs need to accept and respond with JSON to be compatible with a wide range of clients.

Why use error status codes in REST responses?

Error status codes in REST responses are essential for providing feedback to the client about the success or failure of a request. Using the appropriate status code, the client can quickly determine the request's outcome and take the necessary action. For example, if a client sends a request to a server and receives a 404 status code, they know that server did not find the resource they requested. It allows the client to take the necessary steps to resolve the issue, such as checking the URL or trying again with a different request. Additionally, status codes help to create an organized system of responses. It makes it easier for developers to keep track of their API's responses and ensure consistency across different requests. Since status codes are standardized, developers don't have to reinvent the wheel each time they build an API. It saves them time and energy and makes their APIs more reliable and robust.

The worst thing your API could do is to send back an error message with a status code of "200 OK"!

Why don't to use verbs in URLs?

Verbs should not be used in URLs for resources in REST APIs because they are not part of the Uniform Resource Identifier (URI) standard. We should use URIs to identify resources, not to describe actions. Additionally, using verbs in URLs can make them difficult to read and understand. HTTP verbs should sufficiently describe the action being taken on the resource.

Why to use plural resource nouns in REST APIs?

Using plural resource nouns in REST APIs is a good practice because it helps to create a consistent and intuitive structure for the API. It also makes it easier for developers to understand how the API works and how to use it. Plural resource nouns also make it easier to identify the resource type and to distinguish between different types of resources.

Should you use /book/3/ (singular) or /book/3/ (plural)?
Use the plural form. Why? Considering how well it matches all endpoint types.
GET: /book/3/ is okay, but what about GET: /book/? Is it the first book or all of them? That might not be very clear.

Why don't nest resources in REST APIs?

Nesting resources in REST APIs is not recommended because it can lead to a complex and difficult-to-maintain API structure. It can also make it harder for developers to understand the API and make requests. Additionally, it can lead to increased latency and decreased performance due to the need to traverse multiple levels of nesting. It is better to keep the API structure as flat as possible and use query parameters to filter and sort data. This makes the API simpler to understand and use and can improve performance.

Instead of

GET: /books/7/authors/
Enter fullscreen mode Exit fullscreen mode

Use

GET: /books?authorId=7
Enter fullscreen mode Exit fullscreen mode

Which means get books by author with Id=7

Why are error details required in REST response body?

Error details are required in the REST response body to provide the client with a clear and concise description of the exact issue that occurred. It allows the client to understand the issue and take the necessary steps to resolve it. Additionally, error details can help the client to debug the issue and provide helpful feedback to the server.

How to use status codes consistently in REST APIs?

  1. Use standard HTTP status codes: When designing a REST API, it is essential to use standard HTTP status codes to indicate the success or failure of an API request. Standard status codes include 200 (OK), 201 (Created), 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), and 500 (Internal Server Error). 
  2. Use descriptive error messages: When an API request fails, it is crucial to provide a descriptive error message that explains the reason for the failure. It helps the client understand the problem and take corrective action. 
  3. Use the appropriate status code for the action: When responding to an API request, it is important to use the appropriate status code for the action being performed. For example:
    • a successful POST request should return a 201 (Created) status code, while a failed POST request should return a 400 (Bad Request) status code.  
    • GET: 200 OK
    • POST: 201 Created
    • PUT: 200 OK
    • PATCH: 200 OK
    • DELETE: 204 No Content
  4. Use the same status codes for similar actions: When designing a REST API, it is important to use the same status codes for similar actions. For example, a successful GET request should return a 200 (OK) status code, while a failed GET request should return a 404 (Not Found) status code.  
  5. Use the same status codes across all endpoints: When designing a REST API, it is essential to use them across all endpoints. This helps ensure that the client can interpret the response correctly, regardless of which endpoint is used.

What is the difference between 401 Unauthorized and 403 Forbidden?

The 401 Unauthorized status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The 403 Forbidden status code indicates that the server understood the request but refuses to authorize it. In other words, the client cannot access the requested resource.

When to use 202 Accepted response?

The 202 Accepted response is used to indicate that the request has been accepted for processing, but the processing still needs to be completed. This response is most commonly used for asynchronous operations, such as long-running background tasks. It can also indicate that the request has been accepted, but the server is still processing the request and has yet to determine if it will be successful.

How to apply common sense for the REST APIs? 

  1. Use HTTP methods correctly: Use the correct HTTP method for the desired action. For example, use GET for retrieving data, POST for creating data, PUT for updating data, and DELETE for deleting data.
  2. Use proper status codes: Return the appropriate status code for each request. For example, use 200 OK for successful requests, 400 Bad Request for invalid requests, and 404 Not Found for requests that don't exist. 
  3. Validate all input data before processing it. That will help prevent malicious data from being processed. 
  4. Use authentication to ensure that only authorized users can access the API.  
  5. Use HTTPS to ensure that all data is encrypted and secure. 
  6. Use caching to improve performance and reduce server load. 
  7. Use versioning to ensure that clients use the latest API version. 
  8. Log all requests to help identify and debug issues.

Conclusion

REST is the most popular architectural style for building web APIs. It is simple, easy to use, and well-supported by many programming languages. Additionally, it is based on standard protocols and formats, making it easy to integrate with other systems. To design a REST API that is easy to use and maintain, it is vital to use proper HTTP methods, status codes, and payload formats. Additionally, it is best to keep the API structure as flat as possible and use query parameters to filter and sort data.

Top comments (0)