REST API Best Practices

Hello, Habr! I present to you the translation of the article " REST API Best Practices " by Krishna Srinivasan.

REST is becoming a common approach for presenting services to the outside world. The reason for its popularity is its simplicity, ease of use, access via HTTP and others. There is a misconception that all data accessible through the network is considered REST, but this is not so. In this article, I am going to explain to you some best practices that you should always remember when implementing your own REST application. I would like to hear your experience in REST applications, so if you know the best practies that are not mentioned in this article, please share with us in the comments.

Disclamer: All the best practies are based on my personal experience. If you have a different opinion, feel free to send it to me by email and we will discuss it.

Here is a list of best practices that will be discussed in this article:

1. Endpoints in the URL are a noun, not a verb
2. Plural
3. Documentation
4. Version of your application
5. Pagination
6. Using SSL
7. HTTP methods
8. Effective use of HTTP response codes

1. Endpoints in URL - noun, not verb


One of the most common mistakes made by REST application developers is the use of verbs in naming endpoints. However, this is not the best practice. You should always use nouns instead of verbs.

Example scenario:

We have an order to develop REST web services that provide information about Indian farmers. The service should also implement functionality that provides information such as farmer’s income, crop names, farm addresses and other information related to each farmer. Each farmer has a unique id.

In the same way, services should be implemented that provide information about crops and which farmer owns them.

Best Practice:

We have a single endpoint that is responsible for all actions. The example below shows only one endpoint / farmers for all operations such as add, update, delete. Base implementations have various HTTP methods that are correctly routed for different operations.

• / farmers
• / crops

Not recommended:

Try to avoid using verbs. It is recommended to represent operations inside such formats as JSON, XML, RAML or use HTTP methods. Do not use the following notation:

• / getFarmers
• / updateFarmers
• / deleteFarmers
• / getCrops
• / updateCrops
• / deleteCrops

2. Plural


Use the plural to name your REST services. This is another hot topic for discussion among REST designers - the choice between single or multiple nouns for services.

Best Practice:

• / farmers
• / farmers / {farmer_id}
• / crops
• / crops / {crop_id}

Not recommended:

• / farmer
• / farmer / {farmer_id}

Note:
Although I mention that using the plural is best practice, for some reason, if you stick to the singular, stick to this in all of your services. Do not mix the use of plural and singular. Therefore, I am not talking about bad practice here, but just saying that this is not recommended. Please decide for yourself what is best for your application.

3. Documentation


Software documentation is a common practice for all developers. This practice should be followed when implementing REST applications. Writing useful documentation will help other developers understand your code.
The most common way to document REST applications is through documentation with the endpoints listed in it, and a list of operations for each of them. There are many tools that let you do this automatically.

The following are applications that help document REST services:

DRF Docs
Swagger
Apiary

Please share your experience in documenting your applications in the comments.

4. Version of your application


Any software develops over time. This may require different versions for all major changes to the application. When it comes to the REST version of the application, it becomes one of the most talked about topics among the REST developer community.

There are two general ways to version control REST applications:

1. The version URI.
2. Multimedia version.

Version URI:

A simple example of what the URI version looks like:
host / v2 / farmers
host / v1 / farmers

The following are the main disadvantages of the versioning method using the URI:

  1. Existing URIs are broken, all clients must upgrade to a new URI.
  2. The number of version URIs for management increases, which in turn increases the size of the HTTP cache for storing several versions of URIs. Adding a large number of duplicate URIs can affect the number of cache hits, and thus can decrease the performance of your application.
  3. It is extremely inflexible, we cannot just change the resource or their small set.

Multimedia versioning method:
This approach sends version information in the header of each request. When we change the type and language of the multimedia URI, we will move on to looking at the content based on the header. This method is the most preferred option for version control of REST applications.

Sample header information:

GET / account / 5555 HTTP / 1.1
Accept: application / vnd.farmers.v1 + json

HTTP / 1.1 200 OK
Content-Type: application / vnd.farmers.v1 + json

In the multimedia versioning approach, the client has the ability to choose which version to request from the server. This method looks preferable than the URI approach, but the difficulty arises when caching requests with different versions that are passed through the header. In simple words, when a client caches based on a URI, it is simple, but caching with a key as a multimedia type adds complexity.

5. Pagination


Sending a large amount of data via HTTP is not a good idea. Certainly, performance issues will arise, as serializing large JSON objects will become expensive. Best practice is to split the results into parts, rather than sending all the records at once. Provide the ability to break results on a page using the previous or next links.

If you use pagination in your application, one of the good ways to specify a pagination link is to use the Link HTTP header option.
The following link will be helpful to you.

6. Using SSL


SSL should be! You should always use SSL for your REST application. Access to your application will be carried out from anywhere in the world, and there is no guarantee that secure access will be provided to it. With the growing number of incidents with cybercrime, we must ensure the security of our application.

Standard authentication verification protocols make it easy to protect your application. Do not use basic authentication mechanism. Use Oauth1.Oa or Oaurh2 for the best security of your services. I would recommend Oauth2 personally because of its latest features.

7. HTTP methods


Designing operations on HTTP methods becomes easier when you know the characteristics of all HTTP methods. In one of the previous sections of this article, I insisted on using HTTP methods for operations instead of writing different service names for each operation. This section mainly discusses the behavior of each HTTP method.

The following are two characteristics that must be determined before using the HTTP method:

  • Security: The HTTP method is considered safe when calling this method does not change the state of the data. For example, when you retrieve data using the GET method, it is safe because this method does not update the data on the server side.
  • Idempotency: when you get the same answer, how many times you call the same resource, it is known as idempotent. For example, when you try to update the same data on the server, the response will be the same for every request made with the same data.

Not all methods are safe and idempotent. The following is a list of the methods that are used in REST applications and their properties are shown:

image
REST HTTP methods

The following is a brief overview of each method and recommendations for their use:

  • GET: This method is safe and idempotent. Commonly used to extract information and has no side effects.
  • POST: This method is neither safe nor idempotent. This method is most commonly used to create resources.
  • PUT: this method is idempotent. That's why it's better to use this method instead of POST to update resources. Avoid using POST to update resources.
  • DELETE: as the name suggests, this method is used to delete resources. But this method is not idempotent for all queries.
  • OPTIONS: this method is not used for any manipulation of resources. But it is useful when the client does not know other methods supported for the resource, and using this method, the client can get a different representation of the resource.
  • HEAD: this method is used to request a resource from the server. It is very similar to the GET method, but HEAD should send the request and receive the response only in the header. According to the HTTP specification, this method should not use the body for request and response.

8. Effective use of HTTP response codes


HTTP defines various response codes to indicate to the client various information about operations. Your REST application could effectively use all available HTTP codes to help the client properly configure the response. The following is a list of HTTP response codes:

  • 200 OK is the response to a successful GET, PUT, PATCH or DELETE. This code is also used for POST, which does not lead to creation.
  • 201 Created - This status code is a POST response that leads to creation.
  • 204 No content. This is a response to a successful request that will not return the body (e.g. DELETE request)
  • 304 Not Modified — Use this status code when HTTP caching headers are in operation.
  • 400 Bad Request - this status code indicates that the request is malformed, for example, if the body cannot be analyzed
  • 401 Unauthorized - If authentication data is not specified or invalid. It is also useful to activate the auth popup if using the application from a browser
  • 403 Forbidden - when authentication was successful, but the authenticated user does not have access to the resource
  • 404 Not found - if a non-existent resource is requested
  • 405 Method Not Allowed - when an HTTP method is requested that is not allowed for an authenticated user
  • 410 Gone - This status code indicates that the resource at this endpoint is no longer available. Useful as a protective answer for older API versions.
  • 415 Unsupported Media Type. If an incorrect content type was specified as part of the request
  • 422 Unprocessable Entity - used for error checking
  • 429 Too Many Requests - when a request is rejected due to speed limit

Summary


I hope this article will be helpful in understanding how to create your own REST API. Here are the best practices gathered based on my experience and discussions with friends who worked on REST web services applications.

If you have worked hard on the design of the REST API, and if you feel that this article makes no sense to you, I am glad to hear your feedback. I would like to continue updating this discussion with more proven methods for developing a better API for your application.

Good reading. Thanks for visiting my blog.

Also popular now: