How should I implement a COUNT verb in my RESTful web service?

claymation picture claymation · Mar 22, 2011 · Viewed 14.3k times · Source

I've written a RESTful web service that supports the standard CRUD operations, and that can return a set of objects matching certain criteria (a SEARCH verb), but I'd like to add a higher-order COUNT verb, so clients can count the resources matching search criteria without having to fetch all of them.

A few options that occur to me:

  • Ignoring the HTTP specification and returning the object count in the response body of a HEAD request.

  • Duplicating the SEARCH verb's logic, but making a HEAD request instead of a GET request. The server then would encode the object count in a response header.

  • Defining a new HTTP method, COUNT, that returns the object count in the response body.

I'd prefer the API of the first approach, but I have to strike that option because it's non-compliant. The second approach seems most semantically correct, but the API isn't very convenient: clients will have to deal with response headers, when most of the time they want to be able to do something easy like response.count. So I'm leaning toward the third approach, but I'm concerned about the potential problems involved with defining a new HTTP method.

What would you do?

Answer

Yannick Loiseau picture Yannick Loiseau · Mar 22, 2011

The main purpose of rest is to define a set of resources that you interact with using well defined verbs. You must thus avoid to define your own verbs. The number of resources should be considered as a different resource, with its own uri that you can simply GET. For example:

GET resources?crit1=val1&crit2=val2

returns the list of resources and

GET resources/count?crit1=val1&crit2=val2

Another option is to use the conneg: e.g. Accept: text/uri-list returns the resources list and Accept: text/plain returns only the count