Saturday, April 18, 2020

Spring REST – HTTP OPTIONS Request Handler Example

1. HTTP OPTIONS Method

The HTTP OPTIONS method is used to describe the communication options for the target resource. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
  • If the Request-URI is an asterisk (“*”), the OPTIONS request is intended to apply to the server in general rather than to a specific resource.
  • If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
  • Responses to this method are not cacheable.

2. Add Options handler methods to REST Controller

Next step is to add the handler method to handle OPTIONS request.
EmployeeRESTController.java
@RestController
@RequestMapping(value = "/employee-management", produces = { MediaType.APPLICATION_JSON_VALUE })
public class EmployeeRESTController
{
     @RequestMapping(value="/employees", method = RequestMethod.OPTIONS)
     ResponseEntity<?> collectionOptions()
     {
          return ResponseEntity
                  .ok()
                  .allow(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS)
                  .build();
     }
      
     @RequestMapping(value="/employees/{id}", method = RequestMethod.OPTIONS)
     ResponseEntity<?> singularOptions()
     {
          return ResponseEntity
                  .ok()
                  .allow(HttpMethod.GET, HttpMethod.DELETE, HttpMethod.PUT, HttpMethod.OPTIONS)
                  .build();
     }
 
     //Other APIs
}

3. Demo

To test whether OPTIONS requests are handled correctly or not, test in any REST client plugin or SoapUI.
Hit the URL: HTTP OPTIONS http://localhost:8080/api/rest/employee-management/employees/1
In cURL, we can test by hitting following URL.
Verify Options response - 1
curl -i -X OPTIONS http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/
 
Response:
 
#status#        HTTP/1.1 200 OK
Server          Apache-Coyote/1.1
Content-Length  0
Date            Thu, 02 May 2019 10:41:02 GMT
Allow           GET,POST,OPTIONS
Verify Options response - 2
curl -i -X OPTIONS http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/1
 
Response:
 
#status#        HTTP/1.1 200 OK
Server          Apache-Coyote/1.1
Content-Length  0
Date            Thu, 02 May 2019 10:43:15 GMT
Allow           GET,DELETE,PUT,OPTIONS
Happy Learning !!

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...