DrillLab
第 90 / 105 道90 / 105 · #315

查询参数 vs 路径参数

Query parameters vs Path parameters

先自己答,再往下看Answer it yourself first

一句话:路径参数标识「哪一个资源」/users/42),查询参数描述「怎么取」?page=2&sort=name)。

路径参数查询参数
形式/users/:id/users?role=admin
Express 里读req.params.idreq.query.role
Spring 里读@PathVariable@RequestParam
必填性必填(是路径的一部分)通常可选,有默认值
语义标识资源筛选、排序、分页、字段裁剪

设计判据一句话:「去掉它之后,还是同一个资源吗?」去掉 42 就不知道是谁了 → 路径参数; 去掉 ?page=2还是同一批用户,只是换一页 → 查询参数。

会追问:「密码能放查询参数吗?」——绝对不行。 URL 会进浏览器历史、 服务器访问日志、 Referer 头、CDN 日志 ——即使用了 HTTPS, URL 本身也会被大量记录。 敏感数据放请求体或请求头。
「查询参数有长度限制吗?」—— 规范没有,但实践上服务器和 CDN 通常限制 URL 在 2 KB 到 8 KB。 复杂查询条件多的搜索接口 有时会改用 POST 带 body。

In one line: a path parameter says which resource (/users/42); a query parameter says how you want it (?page=2&sort=name).

Path parameterQuery parameter
Shape/users/:id/users?role=admin
Read in Expressreq.params.idreq.query.role
Read in Spring@PathVariable@RequestParam
Required?Yes — it is part of the pathUsually optional, often with a default
MeaningIdentifies the resourceFiltering, sorting, paging, field selection

One test to decide: “Take it away — is it still the same resource?” Drop the 42 and you no longer know who you mean → path parameter. Drop ?page=2 and it is still the same set of users, just a different page → query parameter.

Follow-up: “Can a password go in a query parameter?” — absolutely not. URLs land in browser history, server access logs, the Referer header and CDN logs. HTTPS encrypts the connection; it does not stop the URL from being written down all over the place. Sensitive values go in the body or a header.
“Is there a length limit on query strings?” — not in the spec, but in practice servers and CDNs cap the URL somewhere between 2 KB and 8 KB. Search endpoints with complex filters sometimes switch to POST with a body for that reason.