Skip to main content

Featured

Java Interview Questions for Senior Full Stack Developer

Please like our page to get latest updates from only full stack

Best Practices for Rest API

Best Practices for Rest API

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 Standard?

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 guidelines

Best 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
GET
Get
POST
Insert
PUT
update
PATCH
Partial 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

Do not use verbs- Its a bad practice to use verbs in rest endpoints
/getAllStudents
/getsStudentWithId
/createNewStudent
/deleteStudentWithId

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 Sucess
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
uest 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 Allowed
A 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 Error
A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

501 Not Implemented
The 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 Gateway
The server was acting as a gateway or proxy and received an invalid response from the upstream server.

503 Service Unavailable
The server cannot handle the request (because it is overloaded or down for maintenance). Generally, this is a temporary state.

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"
   }
  ]
} 

5. Handle Errors with HTTP status codes

It is hard to work with an API that ignores error handling. Avoid sending HTTP 500 with a stacktrace to handle any error. Its very hard for consumer to know the exact error cause. Refer Question 3 HTTP status code response and always return relevant HTTP status code for failed API calls.

6. Version your API

Make the API Version mandatory and do not release an unversioned API. There are 4 techniques to version your API and you can choose as per your convenience.
Different types of Spring Rest Versioning ?
1. URI Path / Path Param – you include the version number in the URL path of the endpoint, for example /v1/students
2. Query Parameters – you pass the version number as a query parameter with specified name, for example / students?version=1
3. Custom HTTP Headers – you define a new header that contains the version number in the request
4. Content Negotiation – the version number is included to the “Accept” header together with accepted content type.
Refer below link to know more about each strategy and its pros and cons:
https://onlyfullstack.blogspot.com/2018/11/spring-rest-versioning.html

7. Swagger for Documentation

Swagger is a widely-used tool to document REST APIs that provides a way to explore the use of a specific API, therefore allowing developers to understand the underlying semantic behavior. It’s a declarative way of adding documentation using annotations which further generates a JSON describing APIs and their usage.
Refer below URL for more information on swagger:
https://onlyfullstack.blogspot.com/2018/11/rest-documentation-with-swagger.html 

Comments

Trending Tutorials

Trending Tutorials

WebSocket With Spring Boot and Angular 6 Tutorial

In this tutorial, we will understand What is WebSocket? Why to use WebSocket? Polling vs Server Sent Events vs WebSocket and WebSocket Example with Spring Boot + Angular 6 + STOMP

Code Coverage with JaCoCo Sonar and Maven

In this tutorial, we will understand the importance of code coverage and how can we setup the Sonar + JaCoCo + Maven to get the code coverage. We will look into Setting up Sonar Server Locally, Integrate JaCoCo plugin with Sonar and Maven for Code Coverage, Find Code Coverage in Eclipse : EclEmma Configuration

Java 8 Features

Learn all about Java 8 features in details

Lambda Expression in Java 8

Ever wonder what Lambda Expression is? What Lambda expressions are compiled to? if no then you should go through this tutorial to know more about Lambda and how they are different than anonymous class.