用于资源收集的 REST url,它按不等于给定值的属性过滤资源 [英] REST url for resource collection, which filters resource by attribute not equal to a given value

查看:26
本文介绍了用于资源收集的 REST url,它按不等于给定值的属性过滤资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设计资源集合的REST url,通过不等于给定值的属性过滤资源?

How to design REST url for resource collection, which filters resource by attribute not equal to a given value?

例如,要获取 8 年级的学生,我们使用

For example, to get the students in 8th grade, we use

GET /students?grade=8

如果我们需要让 8 年级的学生,如何做同样的事情?以及如何设计小于 (<) 、大于 (>) 等?

How to do the same, if we need to get the students not in 8th grade? And how to design for less than (<) , greater than (>) etc ?

推荐答案

一个选项是添加一个额外的查询参数,例如 gradeOperator,您可以在其中传递要在比较时使用的运算符grade 参数的值.例如,

One option would be to add an additional query parameter such as gradeOperator in which you could pass the operator to be used when comparing the value against the grade parameter. E.g.,

GET /students?grade=8&gradeOperator=!%3D

!%3DURL 编码 形式!=,因此您的 REST API 会解编码运算符并将其解释为 grade != 8.

!%3D is the URL-encoded form of !=, so your REST API would de-encode the operator and interpret this as grade != 8.

另一种方法是在 HTTP 请求正文中传递值和运算符.这样的事情可能会起作用(以 JSON 中提供的正文为例):

Another approach would be to pass the value and operator in the HTTP request body. Something like this would potentially work (with the body provided in JSON as an example):

GET /students
Content-Type: application/json

{ "grade": {"value": 8, "operator": "!=" } }

这可能很好,因为您不必在 gradeOperator 中重复grade"这个词,该运算符只是作为 grade 的值嵌套在 JSON 对象中>.

That could be nice since you wouldn't have to repeat the word 'grade' in gradeOperator, the operator is simply nested inside a JSON object as the value of grade.

在任一解决方案中,您都可以定义任意数量的运算符,包括 <>>=<= 等.请确保正确清理您的 API 接收的任何输入运算符,尤其是在数据库查询中使用时,以避免诸如 SQL 注入 攻击.

In either solution, you could potentially define any number of operators, including <, >, >=, <=, etc. Just be sure to properly sanitize any input operators your API receives, especially if used in a DB query, to avoid things like SQL injection attacks.

这篇关于用于资源收集的 REST url,它按不等于给定值的属性过滤资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆