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

前端 未结 3 1041
攒了一身酷
攒了一身酷 2021-02-15 13:47

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

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

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-15 14:44

    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
    

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

    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": "!=" } }
    

    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.

    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.

提交回复
热议问题