mirror of
https://github.com/fastapi/fastapi.git
synced 2026-06-15 11:01:13 -04:00
Compare commits
1 Commits
fix-respon
...
translate-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f36682d4d3 |
@@ -7,13 +7,6 @@ hide:
|
||||
|
||||
## Latest Changes
|
||||
|
||||
## 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
|
||||
|
||||
@@ -143,7 +143,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
|
||||
|
||||
---
|
||||
|
||||
"_프로덕션 Python API를 만들고자 한다면, 저는 **FastAPI**를 강력히 추천합니다. **아름답게 설계**되었고, **사용이 간단**하며, **확장성이 매우 뛰어나** 우리의 API 우선 개발 전략에서 **핵심 구성 요소**가 되었습니다._"
|
||||
"_프로덕션 Python API를 만들고자 한다면, 저는 **FastAPI**를 강력히 추천합니다. **아름답게 설계**되었고, **사용이 간단**하며, **확장성이 매우 뛰어나** 우리의 API 우선 개발 전략에서 **핵심 구성 요소**가 되었고, 우리의 Virtual TAC Engineer와 같은 여러 자동화와 서비스들을 추진하고 있습니다._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Deon Pillsbury - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/"><small>(ref)</small></a></div>
|
||||
|
||||
@@ -492,9 +492,7 @@ item: Item
|
||||
|
||||
### 앱 배포하기(선택 사항) { #deploy-your-app-optional }
|
||||
|
||||
선택적으로 FastAPI 앱을 [FastAPI Cloud](https://fastapicloud.com)에 배포할 수 있습니다. 아직이라면 대기자 명단에 등록해 보세요. 🚀
|
||||
|
||||
이미 **FastAPI Cloud** 계정이 있다면(대기자 명단에서 초대해 드렸습니다 😉), 한 번의 명령으로 애플리케이션을 배포할 수 있습니다.
|
||||
선택적으로 FastAPI 앱을 한 번의 명령어로 [FastAPI Cloud](https://fastapicloud.com)에 배포할 수 있습니다. 🚀
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -510,6 +508,8 @@ Deploying to FastAPI Cloud...
|
||||
|
||||
</div>
|
||||
|
||||
CLI가 여러분의 FastAPI 애플리케이션을 자동으로 감지하여 클라우드에 배포합니다. 로그인되어 있지 않다면, 인증을 완료하기 위해 브라우저가 열립니다.
|
||||
|
||||
이게 전부입니다! 이제 해당 URL에서 앱에 접근할 수 있습니다. ✨
|
||||
|
||||
#### FastAPI Cloud 소개 { #about-fastapi-cloud }
|
||||
|
||||
@@ -111,7 +111,7 @@ q: str | None = None
|
||||
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
|
||||
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들과 마찬가지로 동일한 추가 검증과 메타데이터 매개변수를 모두 갖고 있습니다.
|
||||
|
||||
@@ -126,7 +126,7 @@ Pydantic 모델 `Item`에서 가져온 단일 `item` 본문 매개변수만 있
|
||||
하지만 추가 본문 매개변수를 선언할 때처럼, `item` 키를 가지고 그 안에 모델 내용이 들어 있는 JSON을 예상하게 하려면, `Body`의 특별한 매개변수 `embed`를 사용할 수 있습니다:
|
||||
|
||||
```Python
|
||||
item: Item = Body(embed=True)
|
||||
item: Annotated[Item, Body(embed=True)]
|
||||
```
|
||||
|
||||
다음과 같이요:
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 [Pydantic](https://docs.pydantic.dev/) 모델을 사용합니다.
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
|
||||
|
||||
|
||||
@@ -24,13 +24,13 @@
|
||||
|
||||
///
|
||||
|
||||
/// info
|
||||
/// note
|
||||
|
||||
쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
|
||||
|
||||
///
|
||||
|
||||
/// info
|
||||
/// note
|
||||
|
||||
**브라우저는 쿠키를** 내부적으로 특별한 방식으로 처리하기 때문에, **JavaScript**가 쉽게 쿠키를 다루도록 허용하지 않는다는 점을 염두에 두세요.
|
||||
|
||||
|
||||
@@ -72,13 +72,13 @@
|
||||
|
||||
{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 처리*를 지칭합니다.
|
||||
|
||||
///
|
||||
|
||||
/// check | 확인
|
||||
/// tip | 팁
|
||||
|
||||
OpenAPI는 각 *경로 처리*가 응답에 관한 설명을 요구할 것을 명시합니다.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이를 권장하기 시작했습니다).
|
||||
|
||||
@@ -131,7 +131,7 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
|
||||
* `lt`: `l`ess `t`han
|
||||
* `le`: `l`ess than or `e`qual
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`Query`, `Path`, 그리고 나중에 보게 될 다른 클래스들은 공통 `Param` 클래스의 서브클래스입니다.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다.
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
업로드된 파일을 전달받기 위해 먼저 [`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] *}
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`File` 과 `Form` 을 사용하여 파일과 폼 필드를 동시에 정의할 수 있습니다.
|
||||
|
||||
/// info
|
||||
/// note
|
||||
|
||||
업로드된 파일 및/또는 폼 데이터를 받으려면 먼저 [`python-multipart`](https://github.com/Kludex/python-multipart)를 설치해야 합니다.
|
||||
|
||||
|
||||
@@ -12,13 +12,13 @@
|
||||
|
||||
/// note | 참고
|
||||
|
||||
`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 처리 함수*가 아닙니다.
|
||||
`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 다른 매개변수나 본문과 달리, *경로 처리 함수*의 매개변수가 아닙니다.
|
||||
|
||||
///
|
||||
|
||||
`status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다.
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`status_code` 는 파이썬의 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
## `TestClient` 사용하기 { #using-testclient }
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`TestClient` 사용하려면, 우선 [`httpx`](https://www.python-httpx.org)를 설치해야 합니다.
|
||||
|
||||
@@ -144,7 +144,7 @@ FastAPI 애플리케이션에 요청을 보내는 것 외에도 테스트에서
|
||||
|
||||
백엔드로 데이터를 어떻게 보내는지 정보를 더 얻으려면 (`httpx` 혹은 `TestClient`를 이용해서) [HTTPX 문서](https://www.python-httpx.org)를 확인하세요.
|
||||
|
||||
/// info | 정보
|
||||
/// note | 참고
|
||||
|
||||
`TestClient`는 Pydantic 모델이 아니라 JSON으로 변환될 수 있는 데이터를 받습니다.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
||||
|
||||
__version__ = "0.137.1"
|
||||
__version__ = "0.137.0"
|
||||
|
||||
from starlette import status as status
|
||||
|
||||
|
||||
@@ -930,6 +930,28 @@ def _populate_api_route_state(
|
||||
route.path = path
|
||||
route.endpoint = endpoint
|
||||
route.stream_item_type = None
|
||||
if isinstance(response_model, DefaultPlaceholder):
|
||||
return_annotation = get_typed_return_annotation(endpoint)
|
||||
if lenient_issubclass(return_annotation, Response):
|
||||
response_model = None
|
||||
else:
|
||||
stream_item = get_stream_item_type(return_annotation)
|
||||
if stream_item is not None:
|
||||
# Extract item type for JSONL or SSE streaming when
|
||||
# response_class is DefaultPlaceholder (JSONL) or
|
||||
# EventSourceResponse (SSE).
|
||||
# ServerSentEvent is excluded: it's a transport
|
||||
# wrapper, not a data model, so it shouldn't feed
|
||||
# into validation or OpenAPI schema generation.
|
||||
if (
|
||||
isinstance(response_class, DefaultPlaceholder)
|
||||
or lenient_issubclass(response_class, EventSourceResponse)
|
||||
) and not lenient_issubclass(stream_item, ServerSentEvent):
|
||||
route.stream_item_type = stream_item
|
||||
response_model = None
|
||||
else:
|
||||
response_model = return_annotation
|
||||
route.response_model = response_model
|
||||
route.summary = summary
|
||||
route.response_description = response_description
|
||||
route.deprecated = deprecated
|
||||
@@ -965,6 +987,27 @@ def _populate_api_route_state(
|
||||
if isinstance(status_code, IntEnum):
|
||||
status_code = int(status_code)
|
||||
route.status_code = status_code
|
||||
if route.response_model:
|
||||
assert is_body_allowed_for_status_code(status_code), (
|
||||
f"Status code {status_code} must not have a response body"
|
||||
)
|
||||
response_name = "Response_" + route.unique_id
|
||||
route.response_field = create_model_field(
|
||||
name=response_name,
|
||||
type_=route.response_model,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.response_field = None
|
||||
if route.stream_item_type:
|
||||
stream_item_name = "StreamItem_" + route.unique_id
|
||||
route.stream_item_field = create_model_field(
|
||||
name=stream_item_name,
|
||||
type_=route.stream_item_type,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.stream_item_field = None
|
||||
route.dependencies = list(dependencies or [])
|
||||
route.description = description or inspect.cleandoc(route.endpoint.__doc__ or "")
|
||||
# if a "form feed" character (page break) is found in the description text,
|
||||
@@ -1016,88 +1059,9 @@ def _populate_api_route_state(
|
||||
route.is_json_stream = is_generator and isinstance(
|
||||
response_class, DefaultPlaceholder
|
||||
)
|
||||
if isinstance(response_model, DefaultPlaceholder):
|
||||
return_annotation = get_typed_return_annotation(endpoint)
|
||||
if lenient_issubclass(return_annotation, Response):
|
||||
response_model = None
|
||||
else:
|
||||
stream_item = get_stream_item_type(return_annotation)
|
||||
if stream_item is not None and is_generator:
|
||||
# Extract item type for JSONL or SSE streaming for
|
||||
# generator endpoints when response_class is
|
||||
# DefaultPlaceholder (JSONL) or EventSourceResponse
|
||||
# (SSE).
|
||||
# ServerSentEvent is excluded: it's a transport
|
||||
# wrapper, not a data model, so it shouldn't feed
|
||||
# into validation or OpenAPI schema generation.
|
||||
if (
|
||||
isinstance(response_class, DefaultPlaceholder)
|
||||
or lenient_issubclass(response_class, EventSourceResponse)
|
||||
) and not lenient_issubclass(stream_item, ServerSentEvent):
|
||||
route.stream_item_type = stream_item
|
||||
response_model = None
|
||||
else:
|
||||
response_model = return_annotation
|
||||
route.response_model = response_model
|
||||
if route.response_model:
|
||||
assert is_body_allowed_for_status_code(status_code), (
|
||||
f"Status code {status_code} must not have a response body"
|
||||
)
|
||||
response_name = "Response_" + route.unique_id
|
||||
route.response_field = create_model_field(
|
||||
name=response_name,
|
||||
type_=route.response_model,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.response_field = None
|
||||
if route.stream_item_type:
|
||||
stream_item_name = "StreamItem_" + route.unique_id
|
||||
route.stream_item_field = create_model_field(
|
||||
name=stream_item_name,
|
||||
type_=route.stream_item_type,
|
||||
mode="serialization",
|
||||
)
|
||||
else:
|
||||
route.stream_item_field = None
|
||||
|
||||
|
||||
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,
|
||||
@@ -2471,16 +2435,9 @@ class APIRouter(routing.Router):
|
||||
"A path prefix must not end with '/', as the routes will start with '/'"
|
||||
)
|
||||
else:
|
||||
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
|
||||
for r in _iter_included_route_candidates(router.routes):
|
||||
path = getattr(r, "path", None)
|
||||
name = getattr(r, "name", "unknown")
|
||||
if path is not None and not path:
|
||||
raise FastAPIError(
|
||||
f"Prefix and path cannot be both empty (path operation: {name})"
|
||||
|
||||
@@ -2,7 +2,6 @@ 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,
|
||||
@@ -808,60 +807,6 @@ 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()
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import BaseModel
|
||||
@@ -67,21 +65,6 @@ def get_exclude_unset_none() -> ModelDefaults:
|
||||
return ModelDefaults(x=None, y="y")
|
||||
|
||||
|
||||
@app.get("/iterable_exclude_unset", response_model_exclude_unset=True)
|
||||
def get_iterable_exclude_unset() -> Iterable[ModelDefaults]:
|
||||
return [ModelDefaults(x=None, y="y")]
|
||||
|
||||
|
||||
@app.get("/iterable_exclude_defaults", response_model_exclude_defaults=True)
|
||||
def get_iterable_exclude_defaults() -> Iterable[ModelDefaults]:
|
||||
return [ModelDefaults(x=None, y="y")]
|
||||
|
||||
|
||||
@app.get("/iterable_exclude_none", response_model_exclude_none=True)
|
||||
def get_iterable_exclude_none() -> Iterable[ModelDefaults]:
|
||||
return [ModelDefaults(x=None, y="y")]
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
@@ -108,18 +91,3 @@ def test_return_exclude_none():
|
||||
def test_return_exclude_unset_none():
|
||||
response = client.get("/exclude_unset_none")
|
||||
assert response.json() == {"y": "y"}
|
||||
|
||||
|
||||
def test_return_iterable_exclude_unset():
|
||||
response = client.get("/iterable_exclude_unset")
|
||||
assert response.json() == [{"x": None, "y": "y"}]
|
||||
|
||||
|
||||
def test_return_iterable_exclude_defaults():
|
||||
response = client.get("/iterable_exclude_defaults")
|
||||
assert response.json() == [{}]
|
||||
|
||||
|
||||
def test_return_iterable_exclude_none():
|
||||
response = client.get("/iterable_exclude_none")
|
||||
assert response.json() == [{"y": "y", "z": "z"}]
|
||||
|
||||
Reference in New Issue
Block a user