how to handle resource checking on server side? For example, my api looks like:
/books/{id}
After googling i found, that i should use HEAD method to check, if resource exists. https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
I know, that i can use GET endpoint and use HEAD method to fetch information about resource and server does not return body in this case.
But what should i do on server side? I have two options.
One endpoint marked as GET. I this endpoint i can use GET method to fetch data and HEAD to check if resource is available.
Two endpoints. One marked as GET, second as HEAD.
Why i'm considering second solution? Let's assume, that GET request fetch some data from database and process them in some way which takes some time, eg. 10 ms
But what i actually need is only to check if data exists in database. So i can run query like
select count(*) from BOOK where id = :id
and immediately return status 200 if result of query is equal to 1. In this case i don't need to process data so i get a faster response time.
But... resource in REST is a object which is transmitted via HTTP, so maybe i should do processing data but not return them when i use HEAD method?
Thanks in advance for your answer!
You could simply delegate the HEAD
handler to the existing GET
handler and return the status code and headers only (ignoring the response payload).
That's what some frameworks such as Spring MVC and JAX-RS do.
See the following quote from the Spring MVC documentation:
@GetMapping
— and also@RequestMapping(method=HttpMethod.GET)
, are implicitly mapped to and also support HTTPHEAD
. An HTTPHEAD
request is processed as if it were HTTPGET
except but instead of writing the body, the number of bytes are counted and the "Content-Length
header set.[...]
@RequestMapping
method can be explicitly mapped to HTTPHEAD
and HTTPOPTIONS
, but that is not necessary in the common case.
And see the following quote from the JAX-RS documentation:
HEAD
andOPTIONS
requests receive additional automated support. On receipt of aHEAD
request an implementation MUST either:
- Call a method annotated with a request method designator for
HEAD
or, if none present,- Call a method annotated with a request method designator for
GET
and discard any returned entity.Note that option 2 may result in reduced performance where entity creation is significant.
Note: Don't use the old RFC 2616 as reference anymore. It was obsoleted by a new set of RFCs: 7230-7235. For the semantics of the HTTP protocol, refer to the RFC 7231.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With