REST becomes common approach for exposing the services to the outside world. The reason for the popularity is because of it’s simplicity, easy to use, accessed through HTTP (REST can be accessed via any protocols, but most widely used with HTTP), etc. There is a common misconception that any resources exposed through network is considered as REST, but that is not correct. In this tutorial, I am going to explain you some of the best practices that you have to always remember while you are implementing your own REST API.
I would like to hear your experience as a REST API developer. If you have come across any best practices that is not mentioned here, please share with us in the comments section.
- Also Read : REST vs SOAP
Disclamer: these best practices are what I think is good, based from my past experiences. If you think otherwise, feel free to send me an email so we can have a discussion about it.
REST API Design Best Practices
Here is the list of best practices discussed in this tutorial:
- Endpoints as nouns, not verbs
- Use plurals
- Version your API
- Use SSL
- HTTP Methods
- Effectivelu use HTTP Status Codes
1. Endpoints as Nouns, not Verbs
One of the most common bad practice done by the REST API developers are to use the verbs for naming the REST endpoints. However, that is not a best practice. You must always use nouns instead of using verbs.
We have a requirement to expose REST web services for retrieving farmers (agriculturist) details in India. The service also should implement the functionality to retrieve other details like income, crops name, address, etc. which are related to each farmer. Each farmer will have a unique ID assigned to them.
In the similar way, there should be services for exposing the crops details and which farmer has cultivated them.
Have a single endpoint that represents all the operations. In the below example, we expose only one endpoint /farmers for all the operations like get, add, update, delete. The underlying implementations have different HTTP methods that are routed correctly for the different operations. More details provided in the below section for HTTP methods.
Please avoid using the verbs or operations in the naming convention. It is recommended to represent the operation inside the data format (JSON / XML / RAML) or using the HTTP methods. Don’t use the service end points like below:
2. Use Plurals
Use plurals for naming your REST services. This is another hot topic among the REST designers to choose between plural or singular nouns for naming the services.
Note: Though I mention using plural is the good practice, for some reason if you stick to using the singular, then follow the same for all the services. Don’t mix up using plurals and singulars. That is why I am not saying anything as bad practice, I just saying that is not recommended. Please decide yourself which is good for your application.
Documenting the software implementation is the most common practice. This also applies to the REST API implementation. If you write the useful documentation, it will help other programmers to understand.
- Also Read : RESTful Web Service using JAX-RS 2.0
The most common way to document REST APIs is to produce documentation that lists the API endpoints, and describes the list of operations allowed on each endpoint. There are plenty of tools that allow you to do this in an automated way.
Here is some of the tools that may help you to document your REST services:
Please share your experience on documenting your APIs.
4. Version Your API
Any software will evolve over the period of time. This might require a different version for every major changes to the API. When it comes to the REST API version, it is one of the most debated topic among the REST developers community.
There are two common types of versioning for REST API:
- URI Versions
- Media Type Versions
A simple example how a URI version would look like:
The following are the main drawbacks of versioning using URI:
- It breaks the existing URIs, all the clients has to update to the new URI
- It increases the amount of URI versions to manage, this will increase the HTTP caching size of the client to store multiple versions of URI. By adding more number of duplicate URI would affect the percentage of cache hits and it may slow down the performance of your application.
- It is highly inflexible, we can not simply change the single resource or small subset of resources.
Media Type Version
This approach send the version details in the header of each request. When we do change the media type and language of the URI, we will go through content negotiation based on the header. This approach is the most preferred option for the REST API versioning.
Instead sending the generic media types like
application/json, these would be versioned.
Example 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 media type versioning approach, client has the option of choosing the which version to request from the server. This approach looks better than URI version approach, but the complexity arise in caching the requests with different version that are passed through the header. In simple words, when client caches based on the URI, it is simple, But, caching with key as media type adds complexity.
Sending across large amount of data through HTTP is not a good idea.This will certainly come as a performance issue because serializing the large JSON objects become expensive. A best practice is to paginate the results instead of sending all the records at once. Provide option to paginate the results using next or previous links.
If you are using the pagination in your application, one of the good way to indicate the navigation link is to use the
Link HTTP header option.
6. Use SSL
SSL is must. You should always implement SSL for your REST API. Your application will be accessed from every part of the world, there is no guarantee that it will be accessed securely. With the increasing number cyber crime incidents, we must secure our application rightfully.
- Also Read : How to Enable SSL on JBoss Server
Industry standard authentication protocols help reduce the effort of securing your API. Don’t use the basic authentication mechanism. Use either Oauth1.0a or Oauth2 for best security to your services. I would recommend Oauth2 personally for it’s latest features.
If you have any points to share with us, please write it in the comments section.
7. Use HTTP Methods
Mapping operations to HTTP methods is easy when you know the characteristics of all the HTTP methods. One of the previous section in this tutorial I have insisted using the HTTP methods for operations instead of writing the different naming service for each operations. This section primarily deals with behavior of each HTTP methods.
The following are the two characteristics that has to be determined before using a HTTP method:
- Safety : A HTTP method is considered as safe when invoking that method does not change the state of the resource. For example, when you are retrieving a data using the GET method, this is safe because this method does not update the data to back end.
- Idempotent : When you get the same response how many times you invoke the same resource, it is known as idempotent. For example, when you try to update a same data to back end, the response will be same for every request made with same data.
Not all the methods are safe or idempotent. Here is the list of methods that can be used for REST API calls and what are the methods safe and idempotent.
Here is the quick summary of each method and when to use them:
- GET : This method is safe and idempotent. It is always used for retrieving the information and doesn’t have any side effects.
- POST : This method is neither safe nor idempotent. This method is most widely used for creating the resources.
- PUT : This method is idempotent. That is the reason instead POST one can use this method for updating the resources. Avoid using POST for updating the resources.
- DELETE : As the name implies, this method is used for deleting the resources. But, this method is not idempotent for all the requests.
- OPTIONS : This method is not used for any resource manipulation. But, it is useful when client doesn’t know the various methods supported for a resource, using this method client can retrieve the various representation of a resource.
- HEAD : This method used for querying a resource in the server. It is very similar to GET method, but HEAD has to send request and get the response only in the header. As per HTTP specification, this method should not use body for request and response.
8. Effectively Use HTTP Codes
- Also Read : List of HTTP Status Codes and Explanation
HTTP defines various status codes for indicating different meaning to the client. Your REST API could effectively use all the available HTTP codes to help the client route the response accordingly. Here is the list of HTTP status codes for your reference:
- 200 OK – This is response to successful GET, PUT, PATCH or DELETE. This code also be used for a POST that doesn’t result in a creation.
- 201 Created – This status code is response to a POST that results in a creation.
- 204 No Content – This is a response to a successful request that won’t be returning a body (like a DELETE request)
- 304 Not Modified – Use this status code when HTTP caching headers are in play
- 400 Bad Request – This status code indicates that the request is malformed, such as if the body does not parse
- 401 Unauthorized – When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser
- 403 Forbidden – When authentication succeeded but authenticated user doesn’t have access to the resource
- 404 Not Found – When a non-existent resource is requested
- 405 Method Not Allowed – When an HTTP method is being requested that isn’t allowed for the authenticated user
- 410 Gone – This status code indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions
- 415 Unsupported Media Type – If incorrect content type was provided as part of the request
- 422 Unprocessable Entity – Used for validation errors
- 429 Too Many Requests – When a request is rejected due to rate limiting
I hope this tutorial is useful for understanding how to design your REST API. There is nothing called best for the universe, that is applicable for API design. Here the best practices are compiled based on my experience and discussion with friends who worked on the REST web services applications.
If you have worked on REST API design extensively and if you feel that this tutorial not making any sense to you :), I am happy to hear your feedback. I would like to keep updating this space with more proven techniques to design the best API for your application.
Happy reading and have fun :). Thank you for visiting my blog.