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

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

问题描述

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

对我来说,支持分页,排序和分组的系统参数应该位于?"之后但是,诸如状态"和区域"之类的字段或将您的集合细分的其他属性又如何呢?如果这些也要用作查询参数,那么知道何时使用路径参数的经验法则是什么?

解决方案

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

这是一个例子.假设您正在为称为Car的实体实现RESTful API端点.您将这样构造端点:

获取/cars
获取/cars/:id
POST /cars
放置/cars/:id
删除/cars/:id

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

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

获取/cars?color=blue

将实现此端点,以便仅退回蓝色汽车.

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

例如/two-words

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?

解决方案

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.

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
GET /cars/:id
POST /cars
PUT /cars/:id
DELETE /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.

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.

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.

Ex. /two-words

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

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