What’s the best RESTful method to return total number of items in an object?

前端 未结 13 1866
花落未央
花落未央 2020-11-29 15:52

I’m developing a REST API service for a large social networking website I’m involved in. So far, it’s working great. I can issue GET, POST, P

相关标签:
13条回答
  • 2020-11-29 16:19

    While the response to /API/users is paged and returns only 30, records, there's nothing preventing you from including in the response also the total number of records, and other relevant info, like the page size, the page number/offset, etc.

    The StackOverflow API is a good example of that same design. Here's the documentation for the Users method - https://api.stackexchange.com/docs/users

    0 讨论(0)
  • 2020-11-29 16:19

    Alternative when you don't need actual items

    Franci Penov's answer is certainly the best way to go so you always return items along with all additional metadata about your entities being requested. That's the way it should be done.

    but sometimes returning all data doesn't make sense, because you may not need them at all. Maybe all you need is that metadata about your requested resource. Like total count or number of pages or something else. In such case you can always have URL query tell your service not to return items but rather just metadata like:

    /api/members?metaonly=true
    /api/members?includeitems=0
    

    or something similar...

    0 讨论(0)
  • 2020-11-29 16:24

    You could return the count as a custom HTTP header in response to a HEAD request. This way, if a client only wants the count, you don't need to return the actual list, and there's no need for an additional URL.

    (Or, if you're in a controlled environment from endpoint to endpoint, you could use a custom HTTP verb such as COUNT.)

    0 讨论(0)
  • 2020-11-29 16:24

    You could consider counts as a resource. The URL would then be:

    /api/counts/member
    
    0 讨论(0)
  • 2020-11-29 16:25

    What about a new end point > /api/members/count which just calls Members.Count() and returns the result

    0 讨论(0)
  • 2020-11-29 16:28

    I prefer using HTTP Headers for this kind of contextual information.

    For the total number of elements, I use the X-total-count header.
    For links to next, previous page, etc. I use HTTP Link header:
    http://www.w3.org/wiki/LinkHeader

    Github does it the same way: https://developer.github.com/v3/#pagination

    In my opinion, it's cleaner since it can be used also when you return content that doesn't support hyperlinks (i.e binaries, pictures).

    0 讨论(0)
提交回复
热议问题