Moment For Technology

9 Basic PRINCIPLES of REST API design

Posted on Dec. 3, 2022, 9:28 a.m. by Elijah Williamson
Category: The back-end Tag: The back-end

Often, the API design involved in the project development process is to adopt the REST API pattern, but without a strict, understandable, and extensible specification. In the long run, as the project continues to iterate, especially during crunch times, the REST API will drift. Therefore, it is recommended to establish strict API design specifications early in the project.

Personally, I think a good API design specification can avoid a lot of unnecessary communication and improve the efficiency of project development. The interface itself is the document. Here are nine design specifications THAT I feel the REST API must follow.

1. Use HTTP methods to give meaning to endpoints

The REST API encourages the use of a different HTTP method for each CRUD operation of an application. The value can be GET, POST, PUT, DELETE, or PATCH. The name of the endpoint associated with the resource must correspond to the HTTP method associated with the application's operation.

GET /get_articles POST /insert_articles PUT /modify_articles DELETE /delete_articles // Proposed design GET /articles POST  /articles PUT /articles DELETE /articlesCopy the code

2. The status code must be given according to the data results of the API

One of the most important features of an application is that the return of an endpoint is related to the corresponding status code. This means that we can express the data we want to convey in a more descriptive way when our results are success or failure.

For example, if you get status code 200, you immediately know that the result of the API request was a success; otherwise, if you get status code 400, the result is a failure.

It is important to know the existing status codes and to know when to apply them, because the return message may be incorrectly associated with some of the status codes (which is very common), which is very unfriendly to the normal development process and can cause confusion to the developer.

// Bad design {"status": 200, "error": {... }} // Proposed design {"status": 200, "data": [...] }Copy the code

Some common HTTP status codes include:

  • 200: Successful request, usually GET
  • 201: Successful request after creation, usually POST
  • 204: A successful request that returns nothing, usually a PUT or PATCH
  • 301: permanently redirects to another endpoint
  • 400: Wrong request (client should modify request)
  • 401: Unauthorized, credentials not identified
  • 403: Forbidden, credentials accepted but no permissions
  • 404The resource does not exist
  • 410: The resource already exists but does not exist
  • 429: Too many requests for rate limit and should include retry header
  • 500: Server error, is generic, it is worth looking at the other 500 level error
  • 503: Service is not available, where retry header is useful for another service

Filtering, sorting and paging support

Filtering, sorting, and paging are common in applications to help users find the information they need, as well as to reduce server resource consumption (which can be caused by not paging when there is a large amount of data).

  • GET /articles? title=apicate_id=1Filters and retrieves a list of articles with the following attributes: title API, type ID 1
  • GET /articles? limit=10offset=0: Paging to return 10 rows starting from 0.
  • GET /articles? limit=10offset=0sort=ascorder=title: sort, returns the records in ascending order by name.

4. Consistency endpoint design

One of the most common discussions about various KINDS of API development is how do you design the endpoints? Is it singular or plural? In short, we want to maintain consistency in THE DESIGN of the API in our applications, and to do so, we recommend building endpoints in complex form.

A resource does not always have one result, a table may have many results, and even if it has only one result and is singular, it is difficult to keep the routing name format consistent.

GET /article GET /article/:id // Suggested design GET /articles GET /articles/:idCopy the code

5. Name the endpoint with the resource name

Speaking of consistency, if we know that the route is responsible for handling operations on the resource, then it is necessary to name the endpoint directly with the name of the resource, so that when developers use the API, they know what entity data the API is processing.

For example, if you need to increase orders, you can't use /articles as an endpoint, which is very bad.

6. Resource level design

What if we need to access the entity data associated with the resource? To reflect this hierarchy, there are two ways to refer to:

  • Design with endpoint layers
  • Parametric design

Let's take the classic example of "author" and "article."

GET /authors/quintion/articles/rest-api-design GET /articles? author=quintiontitle=rest-api-designCopy the code

These approaches are valid and have been seen on many platforms. Personally, I find it more concise to use a query string than to extend the current path. The more the application expands, the larger the hierarchy we are bound to have, and in turn, the routing expands. Even so, it is based on each person's standard, using the favorite one.

7. Version control

As the project iterates, it is inevitable to have a stable and unambiguous version of the API, free of errors and ambiguity. Suppose we deploy the API and a few clients start using it, what happens when we need to add or remove more data from the resource? Errors may occur on external services that use our interface. This is why we need to have version control over our applications.

There are several ways, but I'm a proponent of the URI version, where we would explicitly have the version of the route in the endpoint.

// URI version v[x] GET /v1/news GET /v2/articlesCopy the code

8. Caching mechanism

Caching is one of the powerful tools that can speed up an API and reduce resource consumption by making requests for the same results and reducing database operations. There are several ways to help us implement caching systems, one of which is file caching, such as Redis.

Of course there is often a cost involved in implementing caching mechanisms, and the principle is to ask: Is the information dynamic or static? If dynamic, how often does the information change?

It is important to know that the cache has a long time of information, which can lead to incorrect API results due to the retention of information for a long time. It is recommended that the cache time be designed to be short.

Design documents

Documentation is one of the best tools for project development and collaboration, and one of the most hated by many developers. In this case, a documented API is essential so that users of our API can understand several important aspects of our interface, including accessibility, responses, requests, and examples.

  • Accessibility: The location and interaction of the interface is one of the most important features, and we didn't want to give customers a manual document. Making our documents public in the cloud for everyone to see is the most convenient thing we can do

  • Responses and requests: The information we provide must consider all possible outcomes of any resource and how to use them.

  • Example: It is important to provide an example of how to use the interface, even if it is a bash script that you can execute in the console and get a response from.

conclusion

How the level of API design can reveal a developer's credentials, and how the best design of an API can be enjoyed by everyone on the project. Of course, there are other principles of a best REST API practice that require consistency among developers.

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.