The HEAD and OPTIONS HTTP methods are used for retrieving metadata about a resource or endpoint. Here's how you can implement and use them in your API:
The HEAD method is used to retrieve the headers of a resource without the response body. It is useful for checking if a resource exists or for retrieving metadata (e.g., Content-Type, Content-Length).
-
Using
curl:curl -I "https://restapiapp.onrender.com/api/students/1"Response:
- If the student exists:
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 0 - If the student does not exist:
HTTP/1.1 404 Not Found Content-Type: application/json Content-Length: 0
- If the student exists:
-
Using Postman:
- Set the HTTP method to HEAD.
- Enter the URL:
https://restapiapp.onrender.com/api/students/1. - Send the request.
- Check the response headers in the "Headers" tab.
-
Using JavaScript (
fetchAPI):fetch('http://localhost:8080/api/students/1', { method: 'HEAD' }) .then(response => { console.log('Status:', response.status); console.log('Headers:', Object.fromEntries(response.headers.entries())); }) .catch(error => console.error(error));
The OPTIONS method is used to retrieve the supported HTTP methods and other communication options for a resource.
Add an OPTIONS method to your StudentController:
// OPTIONS request to retrieve supported methods
@OptionsMapping("/students")
public ResponseEntity<Void> getSupportedMethods() {
return ResponseEntity.ok()
.header("Allow", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS")
.build();
}-
Using
curl:curl -X OPTIONS "https://restapiapp.onrender.com/api/students" -iResponse:
HTTP/1.1 200 OK Allow: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Length: 0 -
Using Postman:
- Set the HTTP method to OPTIONS.
- Enter the URL:
https://restapiapp.onrender.com/api/students. - Send the request.
- Check the response headers in the "Headers" tab.
-
Using JavaScript (
fetchAPI):fetch('https://restapiapp.onrender.com/api/students', { method: 'OPTIONS' }) .then(response => { console.log('Status:', response.status); console.log('Allowed Methods:', response.headers.get('Allow')); }) .catch(error => console.error(error));
-
HEAD:
- Does not return a response body.
- Useful for checking resource existence or retrieving metadata.
- Response status codes:
200 OK: Resource exists.404 Not Found: Resource does not exist.
-
OPTIONS:
- Returns the allowed HTTP methods for the resource.
- Useful for API discovery and documentation.
-
Headers:
- Use the
Acceptheader to specify the desired response format (if applicable). - Use the
Allowheader in theOPTIONSresponse to list supported methods.
- Use the
- HEAD: Use to check if a resource exists or retrieve metadata.
- OPTIONS: Use to discover supported HTTP methods for a resource.
- Both methods are lightweight and do not return a response body.