HEAD vs GET for total count

Viewed 57

What's the better option HEAD or GET? I need to return total count of entities. I've seen a lot of opinions, but not sure what is the most effective. Also not sure if it does make sense to return an Int in the response body or not.

Can HEAD method expect parameters? I ask because the count may be extended in the future with some additional parameters, such as return count of entities which matches the condition I.e. user can pass parameter startsWith etc.

3 Answers

In case of HEAD, you expect server not to send any body, only response headers. In that case you would have to put total count value as custom response header. Performance wise it will not make a big difference. It will be easier for you to handle GET with int in body I think.

If you are expecting to receive a representation of the resource, use GET. If you are expecting only to receive HTTP metadata about the resource, use HEAD.

The HEAD method is identical to GET except that the server MUST NOT send content in the response. HEAD is used to obtain metadata about the selected representation without transferring its representation data, often for the sake of testing hypertext links or finding recent modifications. -- HTTP Semantics 9.3.2


For you, expecting to return data in the body of the response, the correct method to use is GET

GET /count
200 OK
Content-Type: application/json

2

vs

HEAD /count
200 OK
Content-Type: application/json

You can use HEAD and Content-Range and a custom range unit (only bytes are specified).

HEAD /items/

200 OK
Content-Range: count 0-0/1000

Another option is using GET and a different URI:

GET /items/count

200 OK
1000

Afaik. there are request headers which can be used to choose representation type for example the Prefer header could be used, but these headers are rarely used and are very limited. There is another one I don't even remember.

GET /items/
Prefer: return=minimal

200 OK
{count: 1000}
Related