Compare commits

..

7 Commits

Author SHA1 Message Date
github-actions[bot]
4473a0cd91 📝 Update release notes
[skip ci]
2026-06-15 14:31:50 +00:00
Sebastián Ramírez
76876e5a81 🔧 Add ty configs to check docs sources (#15769) 2026-06-15 14:31:14 +00:00
Sebastián Ramírez
a82e5f2fac 🔖 Release version 0.137.1 (#15766)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-06-15 11:26:48 +00:00
github-actions[bot]
edd1461589 📝 Update release notes
[skip ci]
2026-06-15 11:20:24 +00:00
Sebastián Ramírez
b78c82262f 🚨 Fix typing checks for APIRoute (#15765) 2026-06-15 13:19:51 +02:00
github-actions[bot]
e0f8cadf09 📝 Update release notes
[skip ci]
2026-06-15 10:55:32 +00:00
Sebastián Ramírez
d8aad201eb 🐛 Fix bug, allow empty path in path operation in prefixless router (#15763) 2026-06-15 12:55:06 +02:00
17 changed files with 173 additions and 33 deletions

View File

@@ -45,7 +45,7 @@ repos:
- id: local-ty
name: ty check
entry: uv run ty check fastapi
entry: uv run ty check fastapi docs_src --force-exclude
require_serial: true
language: unsupported
pass_filenames: false

View File

@@ -7,6 +7,17 @@ hide:
## Latest Changes
### Internal
* 🔧 Add ty configs to check docs sources. PR [#15769](https://github.com/fastapi/fastapi/pull/15769) by [@tiangolo](https://github.com/tiangolo).
## 0.137.1 (2026-06-15)
### Fixes
* 🚨 Fix typing checks for APIRoute. PR [#15765](https://github.com/fastapi/fastapi/pull/15765) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Fix bug, allow empty path in path operation in prefixless router. PR [#15763](https://github.com/fastapi/fastapi/pull/15763) by [@tiangolo](https://github.com/tiangolo).
## 0.137.0 (2026-06-14)
### Breaking Changes

View File

@@ -492,7 +492,9 @@ item: Item
### 部署你的应用(可选) { #deploy-your-app-optional }
你可以选择用一条命令将 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com)。🚀
你可以选择 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com),如果还没有的话去加入候补名单吧。🚀
如果你已经有 **FastAPI Cloud** 账号(我们从候补名单邀请了你 😉),你可以用一个命令部署你的应用。
<div class="termy">
@@ -508,8 +510,6 @@ Deploying to FastAPI Cloud...
</div>
CLI 会自动检测你的 FastAPI 应用并将其部署到云端。如果你尚未登录,浏览器会打开以完成认证流程。
就这样!现在你可以通过该 URL 访问你的应用了。✨
#### 关于 FastAPI Cloud { #about-fastapi-cloud }

View File

@@ -108,7 +108,7 @@ q: str | None = None
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
/// note | 注意
/// info | 信息
`Body` 同样具有与 `Query``Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
@@ -123,7 +123,7 @@ q: str | None = None
但是,如果你希望它期望一个拥有 `item` 键并在值中包含模型内容的 JSON就像在声明额外的请求体参数时所做的那样则可以使用一个特殊的 `Body` 参数 `embed`
```Python
item: Annotated[Item, Body(embed=True)]
item: Item = Body(embed=True)
```
比如:

View File

@@ -12,7 +12,7 @@
声明 `Cookie` 参数的方式与声明 `Query``Path` 参数相同。
你可以定义默认值,以及所有额外的验证或注参数:
第一个值是默认值,还可以传递所有验证参数或注参数:
{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *}
@@ -24,13 +24,13 @@
///
/// note | 注意
/// info | 信息
必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。
///
/// note | 注意
/// info | 信息
请注意,由于**浏览器会以特殊方式并在幕后处理 cookies**,它们**不会**轻易允许**JavaScript**访问它们。

View File

@@ -42,14 +42,12 @@ $ python myapp.py
那么文件中由 Python 自动创建的内部变量 `__name__`,会将字符串 `"__main__"` 作为值。
所以,这一段
所以,下面这部分代码才会运行
```Python
uvicorn.run(app, host="0.0.0.0", port=8000)
```
会运行。
---
如果你是导入这个模块(文件)就不会这样。
@@ -64,15 +62,13 @@ from myapp import app
在这种情况下,`myapp.py` 内部的自动变量不会有值为 `"__main__"` 的变量 `__name__`
所以,这一行:
所以,下面这一行不会被执行:
```Python
uvicorn.run(app, host="0.0.0.0", port=8000)
```
不会被执行。
/// note | 注意
/// info | 信息
更多信息请检查 [Python 官方文档](https://docs.python.org/3/library/__main__.html).

View File

@@ -56,7 +56,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
## 从 docstring 获取描述 { #description-from-docstring }
描述内容比较长且占用多行时,可以在函数的 <dfn title="作为函数内部的第一个表达式(不赋给任何变量)的多行字符串,用于文档用途">文档字符串</dfn> 中声明*路径操作*的描述,**FastAPI** 会从中读取。
描述内容比较长且占用多行时,可以在函数的 <dfn title="作为函数内部的第一个表达式(不赋给任何变量)的多行字符串,用于文档用途">docstring</dfn> 中声明*路径操作*的描述,**FastAPI** 会从中读取。
文档字符串支持 [Markdown](https://en.wikipedia.org/wiki/Markdown),能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
@@ -72,13 +72,13 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
/// note | 注意
/// info | 信息
注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
///
/// tip | 提示
/// check | 检查
OpenAPI 规定每个*路径操作*都要有响应描述。

View File

@@ -8,7 +8,7 @@
{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
/// note | 注意
/// info | 信息
FastAPI 在 0.95.0 版本添加了对 `Annotated` 的支持(并开始推荐使用它)。
@@ -131,7 +131,7 @@ Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数
* `lt`:小于(`l`ess `t`han
* `le`:小于等于(`l`ess than or `e`qual
/// note | 注意
/// info | 信息
`Query``Path` 以及你后面会看到的其他类,都是一个通用 `Param` 类的子类。
@@ -139,7 +139,7 @@ Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数
///
/// note | 技术细节
/// note | 注意
当你从 `fastapi` 导入 `Query``Path` 和其他对象时,它们实际上是函数。

View File

@@ -2,7 +2,7 @@
你可以使用 `File` 定义由客户端上传的文件。
/// note | 注意
/// info | 信息
要接收上传的文件,请先安装 [`python-multipart`](https://github.com/Kludex/python-multipart)。
@@ -28,7 +28,7 @@ $ pip install python-multipart
{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// note | 注意
/// info | 信息
`File` 是直接继承自 `Form` 的类。

View File

@@ -2,7 +2,7 @@
FastAPI 支持同时使用 `File``Form` 定义文件和表单字段。
/// note | 注意
/// info | 信息
接收上传的文件和/或表单数据,首先安装 [`python-multipart`](https://github.com/Kludex/python-multipart)。

View File

@@ -18,7 +18,7 @@
`status_code` 参数接收表示 HTTP 状态码的数字。
/// note | 注意
/// info | 信息
`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)。

View File

@@ -8,7 +8,7 @@
## 使用 `TestClient` { #using-testclient }
/// note | 注意
/// info | 信息
要使用 `TestClient`,先要安装 [`httpx`](https://www.python-httpx.org)。
@@ -142,7 +142,7 @@ $ pip install httpx
关于如何传数据给后端的更多信息(使用 `httpx` 或 `TestClient`),请查阅 [HTTPX 文档](https://www.python-httpx.org)。
/// note | 注意
/// info | 信息
注意 `TestClient` 接收可以被转化为JSON的数据而不是Pydantic模型。

View File

@@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
__version__ = "0.137.0"
__version__ = "0.137.1"
from starlette import status as status

View File

@@ -1062,6 +1062,41 @@ def _populate_api_route_state(
class APIRoute(routing.Route):
stream_item_type: Any | None
response_model: Any
summary: str | None
response_description: str
deprecated: bool | None
operation_id: str | None
response_model_include: IncEx | None
response_model_exclude: IncEx | None
response_model_by_alias: bool
response_model_exclude_unset: bool
response_model_exclude_defaults: bool
response_model_exclude_none: bool
include_in_schema: bool
response_class: type[Response] | DefaultPlaceholder
dependency_overrides_provider: Any | None
callbacks: list[BaseRoute] | None
openapi_extra: dict[str, Any] | None
generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder
strict_content_type: bool | DefaultPlaceholder
tags: list[str | Enum]
responses: dict[int | str, dict[str, Any]]
unique_id: str
status_code: int | None
response_field: ModelField | None
stream_item_field: ModelField | None
dependencies: list[params.Depends]
description: str
response_fields: dict[int | str, ModelField]
dependant: Dependant
_flat_dependant: Dependant
_embed_body_fields: bool
body_field: ModelField | None
is_sse_stream: bool
is_json_stream: bool
def __init__(
self,
path: str,
@@ -2435,9 +2470,16 @@ class APIRouter(routing.Router):
"A path prefix must not end with '/', as the routes will start with '/'"
)
else:
for r in _iter_included_route_candidates(router.routes):
path = getattr(r, "path", None)
name = getattr(r, "name", "unknown")
for route, route_context in _iter_routes_with_context(router.routes):
if route_context is None:
path = getattr(route, "path", None)
name = getattr(route, "name", "unknown")
elif route_context.starlette_route is not None:
path = getattr(route_context.starlette_route, "path", None)
name = getattr(route_context.starlette_route, "name", "unknown")
else:
path = route_context.path
name = route_context.name
if path is not None and not path:
raise FastAPIError(
f"Prefix and path cannot be both empty (path operation: {name})"

View File

@@ -349,5 +349,41 @@ havin = "havin"
Ines = "Ines"
ser = "ser"
[tool.ty.src]
exclude = [
# These docs examples are intentionally partial, dynamic, environment-driven,
# deprecated, or currently require broader tutorial rewrites to satisfy ty.
"docs_src/additional_status_codes/",
"docs_src/app_testing/tutorial003_py310.py",
"docs_src/body_multiple_params/",
"docs_src/body_updates/tutorial002_py310.py",
"docs_src/custom_docs_ui/",
"docs_src/custom_response/tutorial001_py310.py",
"docs_src/custom_response/tutorial001b_py310.py",
"docs_src/custom_response/tutorial009c_py310.py",
"docs_src/dependencies/tutorial007_py310.py",
"docs_src/dependencies/tutorial008_an_py310.py",
"docs_src/dependencies/tutorial008_py310.py",
"docs_src/dependencies/tutorial010_py310.py",
"docs_src/events/",
"docs_src/extending_openapi/tutorial001_py310.py",
"docs_src/path_params_numeric_validations/",
"docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py",
"docs_src/python_types/tutorial003_py310.py",
"docs_src/python_types/tutorial011_py310.py",
"docs_src/query_params_str_validations/",
"docs_src/response_model/tutorial006_py310.py",
"docs_src/security/tutorial003_an_py310.py",
"docs_src/security/tutorial003_py310.py",
"docs_src/security/tutorial004_an_py310.py",
"docs_src/security/tutorial004_py310.py",
"docs_src/security/tutorial005_an_py310.py",
"docs_src/security/tutorial005_py310.py",
"docs_src/settings/",
"docs_src/sql_databases/",
"docs_src/using_request_directly/tutorial001_py310.py",
"docs_src/wsgi/tutorial001_py310.py",
]
[tool.ty.terminal]
error-on-warning = true

View File

@@ -4,6 +4,6 @@ set -e
set -x
mypy fastapi
ty check fastapi
ty check fastapi docs_src --force-exclude
ruff check fastapi tests docs_src scripts
ruff format fastapi tests --check

View File

@@ -2,6 +2,7 @@ from typing import Annotated, cast
import pytest
from fastapi import APIRouter, Body, Depends, FastAPI, Request
from fastapi.exceptions import FastAPIError
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from fastapi.routing import (
APIRoute,
@@ -807,6 +808,60 @@ def test_no_prefix_include_validation_sees_effective_starlette_route_candidates(
assert cast(Route, candidates[0]).path == "/child/items"
def test_no_prefix_include_validation_sees_effective_api_route_path():
leaf_router = APIRouter()
@leaf_router.get("")
def read_items():
return []
parent_router = APIRouter()
parent_router.include_router(leaf_router, prefix="/items")
# for coverage
candidates = list(_iter_included_route_candidates(parent_router.routes))
assert cast(APIRoute, candidates[0]).path == ""
app = FastAPI()
app.include_router(parent_router)
client = TestClient(app)
response = client.get("/items")
assert response.status_code == 200, response.text
assert response.json() == []
def test_no_prefix_include_validation_sees_effective_starlette_route_path():
def endpoint(request):
return PlainTextResponse("ok")
child_router = APIRouter(routes=[Route("/items", endpoint, name="read_items")])
parent_router = APIRouter()
parent_router.include_router(child_router, prefix="/child")
app = FastAPI()
app.include_router(parent_router)
client = TestClient(app)
response = client.get("/child/items")
assert response.status_code == 200, response.text
assert response.text == "ok"
def test_no_prefix_include_validation_rejects_empty_effective_api_route_path():
router = APIRouter()
@router.get("")
def read_items(): # pragma: no cover
return []
app = FastAPI()
with pytest.raises(FastAPIError):
app.include_router(router)
def test_apirouter_matches_fallback_without_include_context():
router = APIRouter()