Once we are introduced to the REST world, we will be given various options in implementing our web services. At this stage, developers like me usually get confused as to what is the better way. So, here are some of the best practices that need to be remembered when writing RESTful web services.
While writing any RESTful services, we always have to think about the consumers who would like to consume the services in the best way possible. It is supposed to be simple and straightforward to make their job easier.
Consumers need to understand the services so that they can consume them most suitably. Hence, use standard documentation that is simple and straightforward to understand by your consumers.
We can experience this as and when we implement the REST services, I have never come across a situation where I have to implement REST services without using HTTP. Hence, the more we use HTTP, the better RESTful services can be provided.
We must use the proper Request Methods for our services. The consumer will be confused if we use POST for a Delete operation or even a GET mapping to create a new resource.
Note: It is also important to understand the differences between POST and PUT
Most of the consuming services will be implemented according to the Status codes that we provide, and hence we must always provide the most appropriate HTTP Status codes in our response. It will be meaningless if we send a 200 (Status: OK) for a service where the resource is not found or even 500 (Server error) where there is actually a NullPointerException.
Note: More details on HTTP methods and status codes can be found here.
We should not request any information which may be secure in the URI. Consider service to create a new user. It would be good to use POST mapping instead of GET and pass the user information in the Request Body instead of using Path parameters.
It is also important to define a consistent approach to handle any exceptions in the application so it would be easier for the consumer to understand the REST services.
It is strongly advised not to use Verbs in the URI. Instead, we should be using Nouns to make it simpler for the consumers to consume the services. Consider we have two services to retrieve user details and create a new user, /get/users and /create/user is said to be BAD practice. Instead, we should use GET mapping with the URI as /users and a POST mapping with the URI as /users.