我什么时候在 RESTful API 中使用路径参数和查询参数? [英] When do I use path params vs. query params in a RESTful API?

查看:32
本文介绍了我什么时候在 RESTful API 中使用路径参数和查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的 RESTful API 非常可预测.决定何时使用 URI 而不是使用查询参数对数据进行分段的最佳做法是什么.

I want to make my RESTful API very predictable. What is the best practice for deciding when to make a segmentation of data using the URI rather than by using query params.

支持分页、排序和分组的系统参数在?"之后对我来说很有意义.但是,诸如状态"和地区"之类的字段或对您的集合进行细分的其他属性呢?如果这些也是查询参数,那么知道何时使用路径参数的经验法则是什么?

It makes sense to me that system parameters that support pagination, sorting, and grouping be after the '?' But what about fields like 'status' and 'region' or other attributes that segment your collection? If those are to be query params as well, what is the rule of thumb on knowing when to use path params?

推荐答案

RESTful API 设计的最佳实践是使用路径参数来标识一个或多个特定资源,而使用查询参数对这些资源进行排序/过滤.

Best practice for RESTful API design is that path params are used to identify a specific resource or resources, while query parameters are used to sort/filter those resources.

这是一个例子.假设您正在为名为 Car 的实体实现 RESTful API 端点.您可以像这样构建端点:

Here's an example. Suppose you are implementing RESTful API endpoints for an entity called Car. You would structure your endpoints like this:

GET /cars
获取 /cars/:id
POST /cars
PUT /cars/:id
删除 /cars/:id

通过这种方式,您仅在指定要获取的资源时使用路径参数,但这不会以任何方式对资源进行排序/过滤.

This way you are only using path parameters when you are specifying which resource to fetch, but this does not sort/filter the resources in any way.

现在假设您想在 GET 请求中添加按颜色过滤汽车的功能.因为颜色不是资源(它是资源的属性),所以您可以添加执行此操作的查询参数.您可以将该查询参数添加到您的 GET /cars 请求中,如下所示:

Now suppose you wanted to add the capability to filter the cars by color in your GET requests. Because color is not a resource (it is a property of a resource), you could add a query parameter that does this. You would add that query parameter to your GET /cars request like this:

GET /cars?color=blue

将实施此端点,以便仅返回蓝色汽车.

This endpoint would be implemented so that only blue cars would be returned.

就语法而言,您的 URL 名称应全部小写.如果您的实体名称通常由两个英文单词组成,您可以使用连字符来分隔单词,而不是驼峰式大小写.

As far as syntax is concerned, your URL names should be all lowercase. If you have an entity name that is generally two words in English, you would use a hyphen to separate the words, not camel case.

例如./二字

这篇关于我什么时候在 RESTful API 中使用路径参数和查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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