REST API filter operator best practice

后端 未结 4 1713
无人共我
无人共我 2021-02-05 03:21

I am building a REST API that uses a filter parameter to control search results. E.g., one could search for a user by calling:

GET /users/?filter=na         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 03:40

    By embracing a set of common, accepted delimiters, equality comparison can be implemented in straight-forward fashion. Setting the value of the filter query-string parameter to a string using those delimiters creates a list of name/value pairs which can be parsed easily on the server-side and utilized to enhance database queries as needed. You can use the delimeters of your choice say (“|”) to separate individual filter phrases for OR and ("&") to separate individual filter phrases for AND and a double colon (“::”) to separate the names and values. This provides a unique-enough set of delimiters to support the majority of use cases and creates a user readable query-string parameter. A simple example will serve to clarify the technique. Suppose we want to request users with the name “Todd” who live in "Denver" and have the title of “Grand Poobah”.

    The request URI, complete with query-string might look like this:

    GET http://www.example.com/users?filter="name::todd&city::denver&title::grand poobah”

    The delimiter of the double colon (“::”) separates the property name from the comparison value, enabling the comparison value to contain spaces—making it easier to parse the delimiter from the value on the server. Note that the property names in the name/value pairs match the name of the properties that would be returned by the service in the payload.

    Case sensitivity is certainly up for debate on a case-by-case basis, but in general, filtering works best when case is ignored. You can also offer wild-cards as needed using the asterisk (“*”) as the value portion of the name/value pair. For queries that require more-than simple equality or wild-card comparisons, introduction of operators is necessary. In this case, the operators themselves should be part of the value and parsed on the server side, rather than part of the property name. When complex query-language-style functionality is needed, consider introducing query concept from the Open Data Protocol (OData) Filter System Query Option specification (http://www.odata.org/documentation/odata-version-4-0/)

提交回复
热议问题