知识卡片
路径参数可声明类型
在 FastAPI 中,路径模板的 {order_id} 与处理函数的同名参数相连;声明参数为 UUID 后,框架会拒绝不符合该格式的输入。路径变量不只是字符串占位符,类型声明还把一部分输入校验移到了接口边界。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
原书出处
参考来源
- 位置:《Microservice APIs》第 2 章《A basic API implementation》(源文件:_epub-src/OEBPS/Text/02.htm)
- 结论依据:2.3 节明确说明同名路径参数会传给处理函数,并以 UUID 类型提示为例说明不合格式的请求将被判为无效。
- 原始内容:If the name of the parameter matches the name of a URL path parameter, FastAPI passes the path parameter from the URL to our view function on invocation. ... FastAPI allows us to specify the type and format of the URL path parameter by using type hints. In listing 2.4, we specify that order_id ’s type is a universally unique identifier (UUID ). FastAPI will invalidate any calls in which order_id doesn’t follow that format.