简体   繁体   中英

REST service URI design

I am creating a RESTful service which needs to return a collection of items, but also needs to allow for filtering by several indexes (location, Company, and category). These filters can be applied individually or in any combination. Is this a situation where using filters applied in a query string make sense? (some something like: /items?company={}&location={}&category={} ) Is there a better way to pass filters to a resource?

The preferred way to pass search parameters is to use the query string (indeed, that's why it's called the query string). The path identifies the particular resource you want (an index of items). The query string may include, eg, filter conditions, which are used to alter how the resource is represented - but it is still the same resource (an index of items), so the path should be the same.

This is the preferred way in a REST environment. You could POST variables with the filter, but that would violate REST principals (in that the address should represent the resource).

Have you considered using WCF Data Services ? It does a great deal of this for you out-of-the-box in a standards-compliant way.

In your route table you could do something like this:

"items/company/{organizationId?}/{locationId?}/{category?}"

and have your controller action look like this:

public virtual ActionResult Get(string organizationId, string locationId, string category) {
...
}

In my opinion, this beats querystrings as it is much more discoverable.

One simple rule will cover most if not all good practices;

If your filter parameters are optional then they should go to query string, 
if some filters are mandatory you may wanna put them into path. 
Adding optional params to path is not a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM