Table of Contents
Best Practices for Rest API
What have we learned so far,
Part 1 – Spring Rest Advance : Input / Bean Validations
In this post, we discussed the steps to validate the input bean in Spring Rest.
Part 2 – Spring Rest Advance : Rest Documentation with Swagger 2
In this post, we discussed the steps to configure swagger to do the documentation for Spring Rest services
Part 3 – Spring Rest Advance : Spring Boot with H2 DB
In this post, we discussed the steps to configure and use H2 db in spring boot
Part 4 – Spring Rest Advance : Spring Rest Versioning
In this post we discussed the different ways to do the Rest versioning.
Part 5 – Asynchronous Spring Service With @Async And @EnableAsync
In this post we discussed the way to execute a code asynchronously
Part 6 – Spring Profiles
In this post we discussed environment specific Spring profiles
What is REST?
In 2000, Roy Fielding, one of the principal authors of the HTTP specification, proposed an architectural approach for designing web-services known as Representational State Transfer (REST). Note that, while this article assumes REST implementation with HTTP protocol, REST is not tied to HTTP. REST API’s are implemented for a “resource” which could be an entity or service. These API’s provide way to identify a resource by its URI, which can be used to transfer a representation of a resource’s current state over HTTP.Why its important to follow REST Standards?
REST APIs are the face of any service, and therefore they should: 1. Be easy to understand so that integration is straightforward 2. Be well documented, so that semantic behaviors are understood (not just syntactic) 3. Follow accepted standards such as HTTP so it becomes easy for consumers to consume 4. You and consumer comes on the page by following the guidelinesBest practices to build Rest API
1. Use nouns but no verbs Always use the nouns and avoid verbs, Suppose we have to expose the rest endpoint for student and we should have below rest endpoints with supporting HTTP methods.Resource | GETGet | POSTInsert | PUTupdate | PATCHPartial update | DELETE |
/students | Returns a list of all students | Creates a new student | Bulk update of student | Method not allowed(405) | Delete all students |
/students/23 | Returns specific student | Method not allowed(405) | Updates specific student | Partially updates specific student | Deletes specific student |
2. Use HTTP methods to perform operation
Always use HTTP method to do the respective operations on resource. as per the table given in point 1. GET should only be used to get the records POST should only be used to insert the record PUT should only be used to update the record PATCH should only be used to partially update the record DELETE should only be used to delete the record You should not use POST to update or delete a record.3. Use HTTP status codes
The HTTP standard provides over 70 status codes to describe the return values. We don’t need them all, but there should be used at least a mount of 10.2XX Success
This class of status codes indicates the action requested by the client was received, understood and accepted.
200 OK
Standard response for successful HTTP requests. The actual response will depend on the request method used.
HTTP Methods allowed to send this code as part of there response
1. In a GET request, the response will contain an entity corresponding to the requested resource.
2. In a POST request, the response will contain an entity describing or containing the result of the action.
201 Created
The request has been fulfilled, resulting in the creation of a new resource.
HTTP Methods allowed to send this code as part of there response
Only POST is allowed to send this response code after successful creation of the resource.
204 No Content
The server successfully processed the request and is not returning any content.
HTTP Methods allowed to send this code as part of there response
1. In a DELETE response, when server successfully deletes the resource.
2. In a POST response, when server successfully deletes the resource.
4xx Client errors
This class of status code is intended for situations in which the error seems to have been caused by the client. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents should display any included entity to the user.400 – Bad Request
The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing)
The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. „The JSON is not valid“
HTTP Methods allowed to send this code as part of there response
You should send this response code when consumer sends the invalid data as a payload irrespective of any HTTP method.
401 – Unauthorized
specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
HTTP Methods allowed to send this code as part of there response
You should send this response code when the consumer tries to access unauthorised resources irrespective of any HTTP method.
403 – Forbidden
Client was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account of some sort. This code is also typically used if the request provided authentication via the WWW-Authenticate header field, but the server did not accept that authentication.
HTTP Methods allowed to send this code as part of there response
You should send this response code when the consumer tries to access unauthorised resources irrespective of any HTTP method.
404 – Not found
The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
405 Method Not AllowedA request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
5xx Server errors
The server failed to fulfill a request.Response status codes beginning with the digit “5” indicate cases in which the server is aware that it has encountered an error or is otherwise incapable of performing the request. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and indicate whether it is a temporary or permanent condition. Likewise, user agents should display any included entity to the user. These response codes are applicable to any request method.500 Internal Server ErrorA generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
501 Not ImplementedThe server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability (e.g., a new feature of a web-service API).[64]
502 Bad GatewayThe server was acting as a gateway or proxy and received an invalid response from the upstream server.
503 Service UnavailableThe server cannot handle the request (because it is overloaded or down for maintenance). Generally, this is a temporary state.All HTTP Status Codes
4. Use error payloads
All exceptions should be mapped in an error payload. Here is an example how a JSON payload should look like.{ "errors": [ { "userMessage": "Sorry, the requested resource does not exist", "internalMessage": "No student found in the database", "more info": "https://onlyfullstack.blogspot.com" } ] }