Spring REST – HTTP OPTIONS Request Handler Example

Learn to handle the HTTP OPTIONS requests specific to REST resource in Spring webmvc applications by adding specific handler method for RequestMethod.OPTIONS.

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.

@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.

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
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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.