REST OPTIONS method with Example – RESTful Web Services Tutorial

4 weeks ago codedestine 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
Allow: HEAD,GET,PUT,DELETE,OPTIONS

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.

REST OPTIONS 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.

import javax.ws.rs.OPTIONS;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("books")
public class OptionsMethodExample {

  @OPTIONS
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/")
  public Response optionsForBookResource() {		
      return Response.status(200)
		.header("Allow","POST, PUT, GET")
		.header("Content-Type", MediaType.APPLICATION_JSON)
		.header("Content-Length", "0")
		.build();
  }
	
}

Result :-

REST OPTIONS

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.