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

前端 未结 13 1960
花落未央
花落未央 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:28

    As of "X-"-Prefix was deprecated. (see: https://tools.ietf.org/html/rfc6648)

    We found the "Accept-Ranges" as being the best bet to map the pagination ranging: https://tools.ietf.org/html/rfc7233#section-2.3 As the "Range Units" may either be "bytes" or "token". Both do not represent a custom data type. (see: https://tools.ietf.org/html/rfc7233#section-4.2) Still, it is stated that

    HTTP/1.1 implementations MAY ignore ranges specified using other units.

    Which indicates: using custom Range Units is not against the protocol, but it MAY be ignored.

    This way, we would have to set the Accept-Ranges to "members" or whatever ranged unit type, we'd expect. And in addition, also set the Content-Range to the current range. (see: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.12)

    Either way, I would stick to the recommendation of RFC7233 (https://tools.ietf.org/html/rfc7233#page-8) to send a 206 instead of 200:

    If all of the preconditions are true, the server supports the Range
    header field for the target resource, and the specified range(s) are
    valid and satisfiable (as defined in Section 2.1), the server SHOULD
    send a 206 (Partial Content) response with a payload containing one
    or more partial representations that correspond to the satisfiable
    ranges requested, as defined in Section 4.

    So, as a result, we would have the following HTTP header fields:

    For Partial Content:

    206 Partial Content
    Accept-Ranges: members
    Content-Range: members 0-20/100
    

    For full Content:

    200 OK
    Accept-Ranges: members
    Content-Range: members 0-20/20
    

提交回复
热议问题