What's a RESTful way to query with filters?

痴心易碎 提交于 2020-01-04 06:13:18

问题


Say my application is managing objects called workload, with the following fields. I want to expose a REST interface for user to query workloads by labels.

"Workload": {"id":"test1", "labels":["A", "B", "C"]}
"Workload": {"id":"test2", "labels":["A", "C", "D"]}
"Workload": {"id":"test3", "labels":["A", "B", "D"]}

Question: How do I design the REST endpoint so that it would supports query workload by multiple labels as filter?

Sample Query 1: I want to GET all the workloads with both "A" and "B".

I'm thinking something like GET as verb, workloads as endpoint, then use a {"labels": ["A", "B"]} as request body. But this does not seem like a RESTful way to do things

Alternatively, I can do GET /labels/{label-id}/workloads but this would only work with one label per time.

Sample Query 2: I want to GET all the workloads with label "A" or "B" but no "C"

No clue how to do this sort of rest api at all, other than ask user to query by A, B, C separately then do proper set operations themselves?

The second query is tracked as another question


回答1:


GET verb not takes request body. You should do something like 'workload /labels/A, B, C '. You then get A,B, C in request query. Make an array with comma separated from request query and find records.




回答2:


Use query parameters, its fine to repeat them.

GET /workloads?label=A&label=B&label=C

For simple cases you could alsoor and not the terms like this.

GET /workloads?or_label=A&or_label=B&label_not=C



回答3:


You have a lot of options the only constraint here, that they should contain A and B. So for example

  • /workloads/?label=["A","B"]
  • /workloads/?label[]=A&label[]=B - aka. query string array
  • /workloads/by/label/A+B/
  • /label/A+B/workloads/

There are existing URI query conventions as well, for example Microsoft Odata. http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html I am not familiar with OData, but according to the docs you should use something like /WorkloadsByLabels(labels=@c)?@c=["A","B"] if you want to follow their approach. Afaik. there is no standard solution to describe complex URI filters.



来源:https://stackoverflow.com/questions/39670102/whats-a-restful-way-to-query-with-filters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!