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 OKServer Apache-Coyote/1.1Content-Length 0Date Thu, 02 May 2019 10:41:02 GMTAllow GET,POST,OPTIONS |
curl -i -X OPTIONS http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/1Response:#status# HTTP/1.1 200 OKServer Apache-Coyote/1.1Content-Length 0Date Thu, 02 May 2019 10:43:15 GMTAllow GET,DELETE,PUT,OPTIONS |
Happy Learning !!
No comments:
Post a Comment