REST OPTIONS method with Example – RESTful Web Services Tutorial

2 years ago Lalit Bhagtani 0

In REST OPTIONS is a method level annotation, this annotation indicates that the following method will respond to the HTTP OPTIONS request only. It is used to request, for information about the communication option available for a resource.

This method allows the client of the REST API to determine, which HTTP method ( GET, HEAD, POST, PUT, DELETE ) can be used for a resource identified by requested URI, without initiating a resource request by using any particular HTTP method. Response to this method are not cacheable.

A 200 OK response should include any header fields like Allow, that determine the communication option implemented by the server and are applicable for a resource identified by requested URI. The response body ( if any ) should also include information about the communication option available for a resource. The format for such a body is not defined by the specification, but might be defined by future extensions to HTTP. If response body is not included then value of Content-Length header field should be 0.

Example :-
200 OK

If request URI is an asterisk sign ( * ), then the OPTIONS method request applies to the server rather than to a specific resource. It can be used as a ping to server for checking its capabilities.

REST OPTIONS method is also used for CORS ( Cross-Origin Resource Sharing ) request. You can read more about CORS here.

Let’s try to understand it with an example.


In this example of REST OPTIONS, we will hit this URL <base URL>/books to get the list of HTTP method allowed for book resource.


public class OptionsMethodExample {

  public Response optionsForBookResource() {		
      return Response.status(200)
		.header("Allow","POST, PUT, GET")
		.header("Content-Type", MediaType.APPLICATION_JSON)
		.header("Content-Length", "0")

Result :-


References :-

  1. @OPTIONS Java Docs

That’s all for REST OPTIONS with Example. If you liked it, please share your thoughts in comments section and share it with others too.