Facebook, GitHub, Google, and many other giants need a way to serve and consume data. In today’s development environment, RESTful apis remain one of the best choices for serving and consuming data.

But have you considered studying industry standards? What are the best practices for designing RESTful apis? In theory, anyone can quickly launch a data API — be it Node.js, Golang, or Python — in less than five minutes.

We’ll explore 13 best practices to consider when building RESTful apis. But first, let’s quickly clarify RESTful apis.

What is a RESTful API?

A RESTful API must meet the following constraints to be called a RESTful API.

  1. Client-server model: RESTful apis follow the client-server model, where the server serves the data and the client connects to the server to consume the data. The interaction between the client and server is through an HTTP (S) request, which transmits the requested data.
  2. Stateless: More importantly, RESTful apis should be stateless. Each request is treated as a separate request. The server should not track any internal state that could affect the outcome of future requests.
  3. Unified interfaceFinally, consistency defines how clients and servers interact. RESTful apis define best practices for naming resources, but define fixed HTTP operations that allow you to modify/interact with resources. You can access the following HTTP operations from the RESTful API:
    • GET request: Retrieves the resource
    • POST request: Creates a resource or sends information to the API
    • PUT request: Creates or replaces a resource
    • PATCH request: Update existing resources
    • DELETE request: Deletes the resource

Now that you have a better understanding of RESTful apis’ features, it’s time to learn more about RESTful apis’ best practices.

This article provides you with a workable list of 13 best practices. Let’s explore!

1. Use HTTP correctly

We have discussed the HTTP methods that can be used to modify resources: GET, POST, PUT, PATCH, and DELETE.

Still, many developers tend to abuse GET and POST or PUT and PATCH. Typically, we see developers using POST requests to retrieve data. In addition, we see developers using PUT requests to replace resources where they only want to update a single field of the resource.

Make sure to use the correct HTTP methods, as this can add a lot of confusion to developers using your RESTful apis. It is best to stick to predetermined guidelines.

Naming conventions

Understanding RESTful API naming conventions will help you organize your API design. Design a RESTful API based on the resources of your service.

For example, your API manages authors and books (yes, a classic example). Now we need to add a new author or access an author with ID 3. You can design the following routes to achieve this:

  • api.com/addNewAuthor
  • api.com/getAuthorByID/3

Imagine an API hosting many resources, each with many properties. The list of possible endpoints becomes endless and not very user friendly. So we need a more methodical and standardized way to design API endpoints.

RESTful API best practices describe that endpoints should start with resource names, while HTTP operations describe operations. Now we get:

  • POST api.com/authors
  • GET api.com/authors/3

What if we want to access all the books that the author with ID 3 has ever written? RESTful apis also have solutions for this situation:

  • GET api.com/authors/3/books

Finally, what if you want to delete the book WITH ID 5 for the author with ID 3? Again, let’s follow the same structured approach to form the following endpoints:

  • DELETE api.com/authors/3/books/5

In short, use HTTP operations and resource maps in a structured way to form easy-to-understand endpoint paths. The biggest advantage of this approach is that every developer understands how RESTful apis are designed, and they can use the API immediately without having to read your documentation for every endpoint.

3. Use plural sources

Resources should always be in their plural form. Why is that? Suppose you want to retrieve all authors. Therefore, you will invoke the following endpoint: GET api.com/authors.

When you read the request, you cannot tell whether the API response contains only one or all authors. Therefore, API endpoints should use complex resources.

4. Use the status code correctly

Status codes here are not just for fun; they serve a clear purpose. Status codes inform the client of the success of the request.

The most common types of status codes include:

  • 200 (OK) : The request was successfully processed and completed.
  • 201 (Created) : indicates that a resource is Created successfully.
  • 400 (Bad Request) : indicates a client error. That is, the request is ill-formed or the request parameters are missing.
  • 401 (Unauthorized) : You attempt to access resources for which you do not have permission.
  • 404 (Not Found) : The requested resource does Not exist.
  • 500 (Internal Server Error) : Internal Server Error. The Server raises an exception during the execution of the request.

A complete list of status codes can be found at Mozilla Developers.

5. Follow the same conventions

Most commonly, RESTful apis provide JSON data, so you should follow the camelCase case convention. However, different programming languages use different naming conventions.

6. How to handle search, paging, filtering, and sorting

Operations such as search, paging, filtering, and sorting do not represent individual endpoints. This can be done by using the query parameters provided with the API request.

For example, let’s retrieve all authors in ascending order by name. Your API request should look like this: api.com/authors?sort=name_asc.

Also, I want to retrieve an author named “Michiel”. The request looks like this api.com/authors?search=Michiel.

Fortunately, many API projects come with built-in search, paging, filtering, and sorting capabilities. This will save you a lot of time.

7.API version control

I don’t see this very often, but it’s a best practice for versioning your API. This is an effective way to communicate significant changes to your audience.

Usually, API version number included in the API URL, for example: api.com/v1/authors/3/books.

8. Send metadata via HTTP

HTTP headers allow clients to send additional information along with their requests. For example, Authorization headers are typically used to send authentication data to access apis.

You can find a complete list of all possible HTTP headers here.

9. The speed limit

Rate limits are an interesting way to control the number of requests per client. These are the rate limit headers that the server may return:

  • X-rate-limit-limit: tells the client the number of requests that can be sent within a specified interval.
  • X-rate-limit-remaining: tells the client how many requests it can still send in the current interval.
  • X-rate-limit-reset: tells the client when the Rate Limit is Reset.

10. Meaningful error handling

It is important to provide meaningful error messages to developers if problems occur. For example, the Twilio API returns the following error format:

{
  "status": 400."message": "Resource books does not exist"."code": 24801."more_info": "api.com/docs/errors/24801"
}
Copy the code

In this example, the server returns a status code and a human-readable message. In addition, an internal error code is returned for the developer to find a particular error, which allows the developer to quickly find more information about the error.

11. Choose the right API framework

There are many frameworks for different programming languages, and it is important to choose one that supports RESTful API best practices.

For Node.js, back-end developers prefer express.js and Koa, while Falcon is a good choice for Python.

Document your API

Finally, document! I’m not kidding, this is still one of the easiest ways to pass on your knowledge of newly developed apis.

While your API follows all of the best practices outlined by RESTful apis, it’s still worth your time to keep track of various elements, such as the resources the API processes or the rate limit applied to the server.

Think of your fellow developers, documentation drastically reduces the time it takes to learn the API.

13. Keep things simple!

Don’t make your API too complex and keep your resources simple. Correctly defining the different resources your API handles will help you avoid resource-related problems in the future. Define your resource, and also accurately define the relationship between its properties and the resource. That way, there is no room for debate about how to connect different resources.

If you enjoyed this introduction to API best practices, you may also enjoy learning to build RESTful apis from scratch.


First published in the public account “Front-end Full stack Developer”, the first time to read the latest articles, will give priority to two days to publish new articles. After concern private letter reply: gift package, send some network high-quality video course network disk information, can save a lot of money for you!

Original: www.sitepoint.com/build-restf… By Michiel Mulders