REST

REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods
REST uses various representation to represent a resource like text, JSON, XML. JSON is the most popular one.

REST is normally not secure but you can secure it by using Spring security.At the very least you can enable HTTP basic authentication by using HTTP in your Spring security configuration file. Similarly, you can expose your REST API using HTTPS if the underlying server supports HTTPS.

HTTP methods

Following four HTTP methods are commonly used in REST based architecture.
  • GET − Provides a read only access to a resource.
  • POST − Used to create a new resource.
  • DELETE − Used to remove a resource.
  • PUT − Used to update a existing resource or create a new resource.
RESTful Web Services make use of HTTP protocols as a medium of communication between client and server. A client sends a message in form of a HTTP Request and the server responds in the form of an HTTP Response. This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself. Let us have a look on the HTTP Request and HTTP Response messages for HTTP 1.1.

HTTP Request

HTTP Request
An HTTP Request has five major parts −
  • Verb − Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc.
  • URI − Uniform Resource Identifier (URI) to identify the resource on the server.
  • HTTP Version − Indicates the HTTP version. For example, HTTP v1.1.
  • Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc.
  • Request Body − Message content or Resource representation.

HTTP Response

HTTP Response
An HTTP Response has four major parts −
  • Status/Response Code − Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is ok.
  • HTTP Version − Indicates the HTTP version. For example HTTP v1.1.
  • Response Header − Contains metadata for the HTTP Response message as keyvalue pairs. For example, content length, content type, response date, server type, etc.
  • Response Body − Response message content or Resource representation.
Each resource in REST architecture is identified by its URI (Uniform Resource Identifier). A URI is of the following format −
<protocol>://<service-name>/<ResourceType>/<ResourceID>
The following are important points to be considered while designing a URI −
  • Use Plural Noun − Use plural noun to define resources. For example, we've used users to identify users as a resource.
  • Avoid using spaces − Use underscore (_) or hyphen (-) when using a long resource name. For example, use authorized_users instead of authorized%20users.
  • Use lowercase letters − Although URI is case-insensitive, it is a good practice to keep the url in lower case letters only.
  • Maintain Backward Compatibility − As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to a new URI using the HTTP Status code, 300.
  • Use HTTP Verb − Always use HTTP Verb like GET, PUT and DELETE to do the operations on the resource. It is not good to use operations name in the URI.

Example

Following is an example of a poor URI to fetch a user.
http://localhost:8080/UserManagement/rest/UserService/getUser/1 
Following is an example of a good URI to fetch a user.
http://localhost:8080/UserManagement/rest/UserService/users/1

The following table states the examples of the most commonly used HTTP Verbs.
Sr.No.HTTP Method, URI and Operation
1
GET--   http://localhost:8080/UserManagement/rest/UserService/users
Gets the list of users.(Read Only)
2
GET--   http://localhost:8080/UserManagement/rest/UserService/users/1
Gets the User of Id 1(Read Only)
3
PUT--   http://localhost:8080/UserManagement/rest/UserService/users/2
Inserts User with Id 2(Idempotent)
4
POST--  http://localhost:8080/UserManagement/rest/UserService/users/2
Updates the User with Id 2(N/A)
5
DELETE--   http://localhost:8080/UserManagement/rest/UserService/users/1
Deletes the User with Id 1(Idempotent)
6
OPTIONS--  http://localhost:8080/UserManagement/rest/UserService/users
Lists out the supported operations in a web service.(Read Only)
7
HEAD -- http://localhost:8080/UserManagement/rest/UserService/users
Returns the HTTP Header only, no Body.(Read Only)
The following points are to be considered.
  • GET operations are read only and are safe.
  • PUT and DELETE operations are idempotent, which means their result will always be the same, no matter how many times these operations are invoked.
  • PUT and POST operation are nearly the same with the difference lying only in the result where the PUT operation is idempotent and POST operation can cause a different result.
All HTTP response status codes are separated into five classes or categories. The first digit of the status code defines the class of response, while the last two digits do not have any classifying or categorization role. There are five classes defined by the standard:
  • 1xx informational response – the request was received, continuing process
  • 2xx successful – the request was successfully received, understood, and accepted
  • 3xx redirection – further action needs to be taken in order to complete the request
  • 4xx client error – the request contains bad syntax or cannot be fulfilled
  • 5xx server error – the server failed to fulfil an apparently valid request

Sr.No.HTTP Code & Description
1
200      OK − shows success.
2
201       CREATED − when a resource is successfully created using POST or PUT request. Returns link to the newly created resource using the location header.
3
204      NO CONTENT − when response body is empty. For example, a DELETE request.
4
304    NOT MODIFIED − used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty. Headers should have date, location, etc.
5
400       BAD REQUEST − states that an invalid input is provided. For example, validation error, missing data.
6
401       UNAUTHORIZED − states that user is using invalid or wrong authentication token.
7
403    FORBIDDEN − states that the user is not having access to the method being used. For example, Delete access without admin rights.
8
404   NOT FOUND − states that the method is not available.
9
409   CONFLICT − states conflict situation while executing the method. For example, adding duplicate entry.
10
500    INTERNAL SERVER ERROR − states that the server has thrown some exception while executing the method.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

There is no strict rule with respect to what status code your REST API should return after a successful DELETE i.e it can return 200 Ok or 204 No Content. In general, if the DELETE operation is successful and the response body is empty return 204. If the DELETE request is successful and the response body is NOT empty, return 200

CRUD is a short form of Create, Read, Update and Delete. In REST API, the POST is used to create a resource, GET is used to read a resource, PUT is used to updated a resource and DELETE is used to remove a resource from the server.


REST is Scalable and interoperable. It doesn't mandate a specific choice of technology either at client or server end. You can use Java, C++, Python or JavaScript to create RESTful Web Services and Consume them at the client end. I suggest you read a good book on REST API

The RestTemplate class is an implementation of Template method pattern in Spring framework. Similar to other popular template classes e.g. JdbcTemplate or JmsTempalte, it also simplifies the interaction with RESTful Web Services on the client side. You can use it to consume a RESTful Web Servicer very easily as shown in this example.


@RequestMapping annotation is used to map web requests to Spring Controller methods. You can map request based upon HTTP methods  e.g. GET and POST and various other parameters. For examples, if you are developing RESTful Web Service using Spring then you can use produces and consumes property along with media type annotation to indicate that this method is only used to produce or consumers JSON as shown below:
@RequestMapping (method = RequestMethod.POST, consumes="application/json")
public Book save(@RequestBody Book aBook) {
   return bookRepository.save(aBook);

 @Controller and @RestController are stereotypes. The @Controller is actually a specialization of Spring's @Component stereotype annotation. This means that class annotated with @Controller will also be automatically be detected by Spring container as part of container's component scanning process.

And, @RestController is a specialization of @Controller for RESTful web service. It not only combines @ResponseBody and @Controller annotation but also gives more meaning to your controller class to clearly indicate that it deals with RESTful requests.

Spring Framework may also use this annotation to provide some more useful features related to REST API development in future.


 @RestController you get the @ResponseBody annotation automatically, which means you don't need to separately annotate your handler methods with @ResponseBody annotation. This makes the development of RESTful web service easier using Spring. You can see here to learn
The @ResponseBody annotation can be put on a method to indicates that the return type should be written directly to the HTTP response body (and not placed in a Model, or interpreted as a view name).

For example:

@RequestMapping(path = "/hello", method = RequestMethod.PUT)
@ResponseBody
public String helloWorld() {
   return "Hello World";
}

Alternatively, you can also use @RestController annotation instead of @Controller annotation. This will remove the need for using @ResponseBody because as discussed in the previous answer, it comes automatically with @RestController annotation.


@ResponseStatus annotation is required during error handling in Spring MVC and REST. Normally when an error or exception is thrown at server side, web server return a blanket HTTP status code 500 - Internal server error.

This may work for a human user but not for REST clients. You need to send them proper status code e.g. 404 if the resource is not found. That's where you can use @ResponseStatus annotation, which allows you to send custom HTTP status code along with proper error message in case of Exception.

In order to use it, you can create custom exceptions and annotated them using @ResponseStatus annotation and proper HTTP status code and reason.

When such exceptions are thrown from controller's handler methods and not handled anywhere else, then appropriate HTTP response with the proper HTTP status code, which you have set is sent to the client.

For example, if you are writing a RESTful Web Service for a library which provides book information then you can use @ResponseStatus to create Exception which returns HTTP response code 404 when a book is not found instead of Internal Server Error (500), as shown below:

 @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Book")  // 404
 public class BookNotFoundException extends RuntimeException {
     // ...
 }

If this Exception is thrown from any handler method then HTTP error code 404 with reason "No such Book" will be returned to the client.

Need Spring MVC in your Java application's class path to develop RESTful web services using Spring framework. It's actually Spring MVC which provides all useful annotations e.g. @RestController@ResponseCode@ResponseBody@RequestBody, and @PathVariable, hence you must spring-mvc.jar or appropriate Maven entry in your pom.xml