FastAPI 类¶
这是 FastAPI 类的参考信息,包含了它所有的参数、属性和方法。
您可以直接从 fastapi 导入 FastAPI 类
from fastapi import FastAPI
fastapi.FastAPI ¶
FastAPI(
*,
debug=False,
routes=None,
title="FastAPI",
summary=None,
description="",
version="0.1.0",
openapi_url="/openapi.json",
openapi_tags=None,
servers=None,
dependencies=None,
default_response_class=Default(JSONResponse),
redirect_slashes=True,
docs_url="/docs",
redoc_url="/redoc",
swagger_ui_oauth2_redirect_url="/docs/oauth2-redirect",
swagger_ui_init_oauth=None,
middleware=None,
exception_handlers=None,
on_startup=None,
on_shutdown=None,
lifespan=None,
terms_of_service=None,
contact=None,
license_info=None,
openapi_prefix="",
root_path="",
root_path_in_servers=True,
responses=None,
callbacks=None,
webhooks=None,
deprecated=None,
include_in_schema=True,
swagger_ui_parameters=None,
generate_unique_id_function=Default(generate_unique_id),
separate_input_output_schemas=True,
openapi_external_docs=None,
strict_content_type=True,
**extra
)
基类: Starlette
FastAPI 应用类,是使用 FastAPI 的主要入口。
阅读更多内容请参考 FastAPI 第一步文档。
示例¶
from fastapi import FastAPI
app = FastAPI()
| 参数 | 描述 |
|---|---|
debug
|
布尔值,指示服务器错误时是否应返回调试跟踪信息。 阅读更多内容请参考 Starlette 应用文档。
类型: |
routes
|
注意:通常不建议使用此参数,它是从 Starlette 继承而来,仅为兼容性提供支持。 用于处理传入的 HTTP 和 WebSocket 请求的路由列表。
类型: |
title
|
API 的标题。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
summary
|
API 的简要摘要。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
description
|
API 的描述。支持 Markdown(使用 CommonMark 语法)。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
version
|
API 的版本。 注意:这是您的应用程序版本,而不是 OpenAPI 规范的版本,也不是所使用的 FastAPI 版本。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
openapi_url
|
提供 OpenAPI 架构的 URL。 如果您将其设置为 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
openapi_tags
|
OpenAPI 使用的标签列表,这些与您在路径操作中可以设置的
标签的顺序可用于指定在诸如 Swagger UI 之类的工具中显示的顺序,这些工具在自动路径 不需要指定所有使用的标签。 未声明的标签可能会被随机组织或根据工具的逻辑进行组织。列表中的每个标签名称必须是唯一的。 每个项目的值是一个
阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例 |
servers
|
包含目标服务器连接信息的 例如,如果您的应用程序从不同的域提供服务,并且您希望在浏览器中使用同一个 Swagger UI 与它们中的每一个进行交互(而不是打开多个浏览器标签),或者如果您想固定可能的 URL,则可以使用它。 如果未提供
列表中的每一项都是一个
阅读更多内容请参考 FastAPI 关于代理后端的文档。 示例 |
dependencies
|
全局依赖项列表,它们将应用于每个路径操作,包括子路由中的操作。 阅读更多内容请参考 FastAPI 关于全局依赖项的文档。 示例
类型: |
default_response_class
|
要使用的默认响应类。 阅读更多内容请参考 FastAPI 关于自定义响应(HTML, Stream, File 等)的文档。 示例
类型: |
redirect_slashes
|
当客户端不使用相同格式时,是否检测并重定向 URL 中的斜杠。 示例 使用此应用程序,如果客户端访问
类型: |
docs_url
|
自动交互式 API 文档的路径。它在浏览器中由 Swagger UI 处理。 默认 URL 是 如果 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
redoc_url
|
由 ReDoc 提供的替代自动交互式 API 文档的路径。 默认 URL 是 如果 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
swagger_ui_oauth2_redirect_url
|
Swagger UI 的 OAuth2 重定向端点。 默认值为 仅当您在 Swagger UI 中使用 OAuth2(带有“授权”按钮)时,才会用到此设置。
类型: |
swagger_ui_init_oauth
|
Swagger UI 的 OAuth2 配置,默认显示在 阅读更多有关可用配置选项的信息,请参考 Swagger UI 文档。
类型: |
middleware
|
类型: |
exception_handlers
|
类型: |
on_startup
|
类型: |
on_shutdown
|
类型: |
lifespan
|
阅读更多内容请参考 FastAPI 关于
类型: |
terms_of_service
|
API 服务条款的 URL。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
contact
|
包含所公开 API 联系信息的字典。 它可以包含多个字段。
它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
license_info
|
包含所公开 API 许可信息的字典。 它可以包含多个字段。
它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于元数据和文档 URL 的文档。 示例
类型: |
openapi_prefix
|
OpenAPI URL 的 URL 前缀。
类型: |
root_path
|
由代理处理的路径前缀,应用程序无法看到,但外部客户端可以看到,这会影响 Swagger UI 等事物。 阅读更多内容请参考 FastAPI 关于代理后端的文档。 示例
类型: |
root_path_in_servers
|
用于禁用在自动生成的 OpenAPI 中使用 阅读更多内容请参考 FastAPI 关于代理后端的文档。 示例
类型: |
responses
|
|
callbacks
|
类型: |
webhooks
|
添加 OpenAPI Webhook。这类似于 它将被添加到生成的 OpenAPI (例如在 注意:OpenAPI 3.1.0 及 FastAPI 0.99.0 起可用。 阅读更多内容请参考 FastAPI 关于 OpenAPI Webhook 的文档。
类型: |
deprecated
|
类型: |
include_in_schema
|
用于在生成的 OpenAPI 中包含(或不包含)所有路径操作。您可能不需要它,但它是可用的。 这会影响生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于查询参数和字符串校验的文档。
类型: |
swagger_ui_parameters
|
用于配置 Swagger UI 的参数,这是自动生成的交互式 API 文档(默认在 阅读更多内容请参考 FastAPI 关于如何配置 Swagger UI 的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
separate_input_output_schemas
|
当结果更精确时,是否为请求体和响应体生成独立的 OpenAPI 架构。 这在自动生成客户端时特别有用。 例如,如果您有一个像这样的模型 当 但当 在这种情况下,会有两个不同的架构:一个用于输入,另一个用于输出。 阅读更多内容请参考 FastAPI 关于如何分离输入和输出架构的文档
类型: |
openapi_external_docs
|
此字段允许您提供额外的外部文档链接。如果提供,它必须是一个包含以下内容的字典:
示例:
类型: |
strict_content_type
|
启用对请求 Content-Type 头的严格检查。 当为 这防止了潜在的跨站请求伪造 (CSRF) 攻击,这些攻击利用浏览器发送不带 Content-Type 头的请求的能力,从而绕过 CORS 预检检查。特别适用于需要在本地(localhost)运行的应用程序。 当为 阅读更多内容请参考 FastAPI 关于严格 Content-Type 的文档。
类型: |
**extra
|
要存储在应用程序中的额外关键字参数,FastAPI 内部任何地方都不会用到。
类型: |
fastapi/applications.py 中的源代码
def __init__(
self: AppType,
*,
debug: Annotated[
bool,
Doc(
"""
Boolean indicating if debug tracebacks should be returned on server
errors.
Read more in the
[Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application).
"""
),
] = False,
routes: Annotated[
list[BaseRoute] | None,
Doc(
"""
**Note**: you probably shouldn't use this parameter, it is inherited
from Starlette and supported for compatibility.
---
A list of routes to serve incoming HTTP and WebSocket requests.
"""
),
deprecated(
"""
You normally wouldn't use this parameter with FastAPI, it is inherited
from Starlette and supported for compatibility.
In FastAPI, you normally would use the *path operation methods*,
like `app.get()`, `app.post()`, etc.
"""
),
] = None,
title: Annotated[
str,
Doc(
"""
The title of the API.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(title="ChimichangApp")
```
"""
),
] = "FastAPI",
summary: Annotated[
str | None,
Doc(
"""
A short summary of the API.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(summary="Deadpond's favorite app. Nuff said.")
```
"""
),
] = None,
description: Annotated[
str,
Doc(
'''
A description of the API. Supports Markdown (using
[CommonMark syntax](https://commonmark.cn/)).
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(
description="""
ChimichangApp API helps you do awesome stuff. 🚀
## Items
You can **read items**.
## Users
You will be able to:
* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""
)
```
'''
),
] = "",
version: Annotated[
str,
Doc(
"""
The version of the API.
**Note** This is the version of your application, not the version of
the OpenAPI specification nor the version of FastAPI being used.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(version="0.0.1")
```
"""
),
] = "0.1.0",
openapi_url: Annotated[
str | None,
Doc(
"""
The URL where the OpenAPI schema will be served from.
If you set it to `None`, no OpenAPI schema will be served publicly, and
the default automatic endpoints `/docs` and `/redoc` will also be
disabled.
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#openapi-url).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(openapi_url="/api/v1/openapi.json")
```
"""
),
] = "/openapi.json",
openapi_tags: Annotated[
list[dict[str, Any]] | None,
Doc(
"""
A list of tags used by OpenAPI, these are the same `tags` you can set
in the *path operations*, like:
* `@app.get("/users/", tags=["users"])`
* `@app.get("/items/", tags=["items"])`
The order of the tags can be used to specify the order shown in
tools like Swagger UI, used in the automatic path `/docs`.
It's not required to specify all the tags used.
The tags that are not declared MAY be organized randomly or based
on the tools' logic. Each tag name in the list MUST be unique.
The value of each item is a `dict` containing:
* `name`: The name of the tag.
* `description`: A short description of the tag.
[CommonMark syntax](https://commonmark.cn/) MAY be used for rich
text representation.
* `externalDocs`: Additional external documentation for this tag. If
provided, it would contain a `dict` with:
* `description`: A short description of the target documentation.
[CommonMark syntax](https://commonmark.cn/) MAY be used for
rich text representation.
* `url`: The URL for the target documentation. Value MUST be in
the form of a URL.
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-tags).
**Example**
```python
from fastapi import FastAPI
tags_metadata = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
},
{
"name": "items",
"description": "Manage items. So _fancy_ they have their own docs.",
"externalDocs": {
"description": "Items external docs",
"url": "https://fastapi.org.cn/",
},
},
]
app = FastAPI(openapi_tags=tags_metadata)
```
"""
),
] = None,
servers: Annotated[
list[dict[str, str | Any]] | None,
Doc(
"""
A `list` of `dict`s with connectivity information to a target server.
You would use it, for example, if your application is served from
different domains and you want to use the same Swagger UI in the
browser to interact with each of them (instead of having multiple
browser tabs open). Or if you want to leave fixed the possible URLs.
If the servers `list` is not provided, or is an empty `list`, the
`servers` property in the generated OpenAPI will be:
* a `dict` with a `url` value of the application's mounting point
(`root_path`) if it's different from `/`.
* otherwise, the `servers` property will be omitted from the OpenAPI
schema.
Each item in the `list` is a `dict` containing:
* `url`: A URL to the target host. This URL supports Server Variables
and MAY be relative, to indicate that the host location is relative
to the location where the OpenAPI document is being served. Variable
substitutions will be made when a variable is named in `{`brackets`}`.
* `description`: An optional string describing the host designated by
the URL. [CommonMark syntax](https://commonmark.cn/) MAY be used for
rich text representation.
* `variables`: A `dict` between a variable name and its value. The value
is used for substitution in the server's URL template.
Read more in the
[FastAPI docs for Behind a Proxy](https://fastapi.org.cn/advanced/behind-a-proxy/#additional-servers).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(
servers=[
{"url": "https://stag.example.com", "description": "Staging environment"},
{"url": "https://prod.example.com", "description": "Production environment"},
]
)
```
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of global dependencies, they will be applied to each
*path operation*, including in sub-routers.
Read more about it in the
[FastAPI docs for Global Dependencies](https://fastapi.org.cn/tutorial/dependencies/global-dependencies/).
**Example**
```python
from fastapi import Depends, FastAPI
from .dependencies import func_dep_1, func_dep_2
app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])
```
"""
),
] = None,
default_response_class: Annotated[
type[Response],
Doc(
"""
The default response class to be used.
Read more in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#default-response-class).
**Example**
```python
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
app = FastAPI(default_response_class=ORJSONResponse)
```
"""
),
] = Default(JSONResponse),
redirect_slashes: Annotated[
bool,
Doc(
"""
Whether to detect and redirect slashes in URLs when the client doesn't
use the same format.
**Example**
```python
from fastapi import FastAPI
app = FastAPI(redirect_slashes=True) # the default
@app.get("/items/")
async def read_items():
return [{"item_id": "Foo"}]
```
With this app, if a client goes to `/items` (without a trailing slash),
they will be automatically redirected with an HTTP status code of 307
to `/items/`.
"""
),
] = True,
docs_url: Annotated[
str | None,
Doc(
"""
The path to the automatic interactive API documentation.
It is handled in the browser by Swagger UI.
The default URL is `/docs`. You can disable it by setting it to `None`.
If `openapi_url` is set to `None`, this will be automatically disabled.
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#docs-urls).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(docs_url="/documentation", redoc_url=None)
```
"""
),
] = "/docs",
redoc_url: Annotated[
str | None,
Doc(
"""
The path to the alternative automatic interactive API documentation
provided by ReDoc.
The default URL is `/redoc`. You can disable it by setting it to `None`.
If `openapi_url` is set to `None`, this will be automatically disabled.
Read more in the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#docs-urls).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")
```
"""
),
] = "/redoc",
swagger_ui_oauth2_redirect_url: Annotated[
str | None,
Doc(
"""
The OAuth2 redirect endpoint for the Swagger UI.
By default it is `/docs/oauth2-redirect`.
This is only used if you use OAuth2 (with the "Authorize" button)
with Swagger UI.
"""
),
] = "/docs/oauth2-redirect",
swagger_ui_init_oauth: Annotated[
dict[str, Any] | None,
Doc(
"""
OAuth2 configuration for the Swagger UI, by default shown at `/docs`.
Read more about the available configuration options in the
[Swagger UI docs](https://swagger.org.cn/docs/open-source-tools/swagger-ui/usage/oauth2/).
"""
),
] = None,
middleware: Annotated[
Sequence[Middleware] | None,
Doc(
"""
List of middleware to be added when creating the application.
In FastAPI you would normally do this with `app.add_middleware()`
instead.
Read more in the
[FastAPI docs for Middleware](https://fastapi.org.cn/tutorial/middleware/).
"""
),
] = None,
exception_handlers: Annotated[
dict[
int | type[Exception],
Callable[[Request, Any], Coroutine[Any, Any, Response]],
]
| None,
Doc(
"""
A dictionary with handlers for exceptions.
In FastAPI, you would normally use the decorator
`@app.exception_handler()`.
Read more in the
[FastAPI docs for Handling Errors](https://fastapi.org.cn/tutorial/handling-errors/).
"""
),
] = None,
on_startup: Annotated[
Sequence[Callable[[], Any]] | None,
Doc(
"""
A list of startup event handler functions.
You should instead use the `lifespan` handlers.
Read more in the [FastAPI docs for `lifespan`](https://fastapi.org.cn/advanced/events/).
"""
),
] = None,
on_shutdown: Annotated[
Sequence[Callable[[], Any]] | None,
Doc(
"""
A list of shutdown event handler functions.
You should instead use the `lifespan` handlers.
Read more in the
[FastAPI docs for `lifespan`](https://fastapi.org.cn/advanced/events/).
"""
),
] = None,
lifespan: Annotated[
Lifespan[AppType] | None,
Doc(
"""
A `Lifespan` context manager handler. This replaces `startup` and
`shutdown` functions with a single context manager.
Read more in the
[FastAPI docs for `lifespan`](https://fastapi.org.cn/advanced/events/).
"""
),
] = None,
terms_of_service: Annotated[
str | None,
Doc(
"""
A URL to the Terms of Service for your API.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more at the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
app = FastAPI(terms_of_service="http://example.com/terms/")
```
"""
),
] = None,
contact: Annotated[
dict[str, str | Any] | None,
Doc(
"""
A dictionary with the contact information for the exposed API.
It can contain several fields.
* `name`: (`str`) The name of the contact person/organization.
* `url`: (`str`) A URL pointing to the contact information. MUST be in
the format of a URL.
* `email`: (`str`) The email address of the contact person/organization.
MUST be in the format of an email address.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more at the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
app = FastAPI(
contact={
"name": "Deadpoolio the Amazing",
"url": "http://x-force.example.com/contact/",
"email": "dp@x-force.example.com",
}
)
```
"""
),
] = None,
license_info: Annotated[
dict[str, str | Any] | None,
Doc(
"""
A dictionary with the license information for the exposed API.
It can contain several fields.
* `name`: (`str`) **REQUIRED** (if a `license_info` is set). The
license name used for the API.
* `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression
for the API. The `identifier` field is mutually exclusive of the `url`
field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.
* `url`: (`str`) A URL to the license used for the API. This MUST be
the format of a URL.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more at the
[FastAPI docs for Metadata and Docs URLs](https://fastapi.org.cn/tutorial/metadata/#metadata-for-api).
**Example**
```python
app = FastAPI(
license_info={
"name": "Apache 2.0",
"url": "https://apache.ac.cn/licenses/LICENSE-2.0.html",
}
)
```
"""
),
] = None,
openapi_prefix: Annotated[
str,
Doc(
"""
A URL prefix for the OpenAPI URL.
"""
),
deprecated(
"""
"openapi_prefix" has been deprecated in favor of "root_path", which
follows more closely the ASGI standard, is simpler, and more
automatic.
"""
),
] = "",
root_path: Annotated[
str,
Doc(
"""
A path prefix handled by a proxy that is not seen by the application
but is seen by external clients, which affects things like Swagger UI.
Read more about it at the
[FastAPI docs for Behind a Proxy](https://fastapi.org.cn/advanced/behind-a-proxy/).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(root_path="/api/v1")
```
"""
),
] = "",
root_path_in_servers: Annotated[
bool,
Doc(
"""
To disable automatically generating the URLs in the `servers` field
in the autogenerated OpenAPI using the `root_path`.
Read more about it in the
[FastAPI docs for Behind a Proxy](https://fastapi.org.cn/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).
**Example**
```python
from fastapi import FastAPI
app = FastAPI(root_path_in_servers=False)
```
"""
),
] = True,
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses to be shown in OpenAPI.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Additional Responses in OpenAPI](https://fastapi.org.cn/advanced/additional-responses/).
And in the
[FastAPI docs for Bigger Applications](https://fastapi.org.cn/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
OpenAPI callbacks that should apply to all *path operations*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
webhooks: Annotated[
routing.APIRouter | None,
Doc(
"""
Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't
depend on specific *path operations*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
**Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.
Read more about it in the
[FastAPI docs for OpenAPI Webhooks](https://fastapi.org.cn/advanced/openapi-webhooks/).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark all *path operations* as deprecated. You probably don't need it,
but it's available.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#deprecate-a-path-operation).
"""
),
] = None,
include_in_schema: Annotated[
bool,
Doc(
"""
To include (or not) all the *path operations* in the generated OpenAPI.
You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
swagger_ui_parameters: Annotated[
dict[str, Any] | None,
Doc(
"""
Parameters to configure Swagger UI, the autogenerated interactive API
documentation (by default at `/docs`).
Read more about it in the
[FastAPI docs about how to Configure Swagger UI](https://fastapi.org.cn/how-to/configure-swagger-ui/).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
separate_input_output_schemas: Annotated[
bool,
Doc(
"""
Whether to generate separate OpenAPI schemas for request body and
response body when the results would be more precise.
This is particularly useful when automatically generating clients.
For example, if you have a model like:
```python
from pydantic import BaseModel
class Item(BaseModel):
name: str
tags: list[str] = []
```
When `Item` is used for input, a request body, `tags` is not required,
the client doesn't have to provide it.
But when using `Item` for output, for a response body, `tags` is always
available because it has a default value, even if it's just an empty
list. So, the client should be able to always expect it.
In this case, there would be two different schemas, one for input and
another one for output.
Read more about it in the
[FastAPI docs about how to separate schemas for input and output](https://fastapi.org.cn/how-to/separate-openapi-schemas)
"""
),
] = True,
openapi_external_docs: Annotated[
dict[str, Any] | None,
Doc(
"""
This field allows you to provide additional external documentation links.
If provided, it must be a dictionary containing:
* `description`: A brief description of the external documentation.
* `url`: The URL pointing to the external documentation. The value **MUST**
be a valid URL format.
**Example**:
```python
from fastapi import FastAPI
external_docs = {
"description": "Detailed API Reference",
"url": "https://example.com/api-docs",
}
app = FastAPI(openapi_external_docs=external_docs)
```
"""
),
] = None,
strict_content_type: Annotated[
bool,
Doc(
"""
Enable strict checking for request Content-Type headers.
When `True` (the default), requests with a body that do not include
a `Content-Type` header will **not** be parsed as JSON.
This prevents potential cross-site request forgery (CSRF) attacks
that exploit the browser's ability to send requests without a
Content-Type header, bypassing CORS preflight checks. In particular
applicable for apps that need to be run locally (in localhost).
When `False`, requests without a `Content-Type` header will have
their body parsed as JSON, which maintains compatibility with
certain clients that don't send `Content-Type` headers.
Read more about it in the
[FastAPI docs for Strict Content-Type](https://fastapi.org.cn/advanced/strict-content-type/).
"""
),
] = True,
**extra: Annotated[
Any,
Doc(
"""
Extra keyword arguments to be stored in the app, not used by FastAPI
anywhere.
"""
),
],
) -> None:
self.debug = debug
self.title = title
self.summary = summary
self.description = description
self.version = version
self.terms_of_service = terms_of_service
self.contact = contact
self.license_info = license_info
self.openapi_url = openapi_url
self.openapi_tags = openapi_tags
self.root_path_in_servers = root_path_in_servers
self.docs_url = docs_url
self.redoc_url = redoc_url
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
self.swagger_ui_init_oauth = swagger_ui_init_oauth
self.swagger_ui_parameters = swagger_ui_parameters
self.servers = servers or []
self.separate_input_output_schemas = separate_input_output_schemas
self.openapi_external_docs = openapi_external_docs
self.extra = extra
self.openapi_version: Annotated[
str,
Doc(
"""
The version string of OpenAPI.
FastAPI will generate OpenAPI version 3.1.0, and will output that as
the OpenAPI version. But some tools, even though they might be
compatible with OpenAPI 3.1.0, might not recognize it as a valid.
So you could override this value to trick those tools into using
the generated OpenAPI. Have in mind that this is a hack. But if you
avoid using features added in OpenAPI 3.1.0, it might work for your
use case.
This is not passed as a parameter to the `FastAPI` class to avoid
giving the false idea that FastAPI would generate a different OpenAPI
schema. It is only available as an attribute.
**Example**
```python
from fastapi import FastAPI
app = FastAPI()
app.openapi_version = "3.0.2"
```
"""
),
] = "3.1.0"
self.openapi_schema: dict[str, Any] | None = None
if self.openapi_url:
assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
# TODO: remove when discarding the openapi_prefix parameter
if openapi_prefix:
logger.warning(
'"openapi_prefix" has been deprecated in favor of "root_path", which '
"follows more closely the ASGI standard, is simpler, and more "
"automatic. Check the docs at "
"https://fastapi.org.cn/advanced/sub-applications/"
)
self.webhooks: Annotated[
routing.APIRouter,
Doc(
"""
The `app.webhooks` attribute is an `APIRouter` with the *path
operations* that will be used just for documentation of webhooks.
Read more about it in the
[FastAPI docs for OpenAPI Webhooks](https://fastapi.org.cn/advanced/openapi-webhooks/).
"""
),
] = webhooks or routing.APIRouter()
self.root_path = root_path or openapi_prefix
self.state: Annotated[
State,
Doc(
"""
A state object for the application. This is the same object for the
entire application, it doesn't change from request to request.
You normally wouldn't use this in FastAPI, for most of the cases you
would instead use FastAPI dependencies.
This is simply inherited from Starlette.
Read more about it in the
[Starlette docs for Applications](https://www.starlette.dev/applications/#storing-state-on-the-app-instance).
"""
),
] = State()
self.dependency_overrides: Annotated[
dict[Callable[..., Any], Callable[..., Any]],
Doc(
"""
A dictionary with overrides for the dependencies.
Each key is the original dependency callable, and the value is the
actual dependency that should be called.
This is for testing, to replace expensive dependencies with testing
versions.
Read more about it in the
[FastAPI docs for Testing Dependencies with Overrides](https://fastapi.org.cn/advanced/testing-dependencies/).
"""
),
] = {}
self.router: routing.APIRouter = routing.APIRouter(
routes=routes,
redirect_slashes=redirect_slashes,
dependency_overrides_provider=self,
on_startup=on_startup,
on_shutdown=on_shutdown,
lifespan=lifespan,
default_response_class=default_response_class,
dependencies=dependencies,
callbacks=callbacks,
deprecated=deprecated,
include_in_schema=include_in_schema,
responses=responses,
generate_unique_id_function=generate_unique_id_function,
strict_content_type=strict_content_type,
)
self.exception_handlers: dict[
Any, Callable[[Request, Any], Response | Awaitable[Response]]
] = {} if exception_handlers is None else dict(exception_handlers)
self.exception_handlers.setdefault(HTTPException, http_exception_handler)
self.exception_handlers.setdefault(
RequestValidationError, request_validation_exception_handler
)
# Starlette still has incorrect type specification for the handlers
self.exception_handlers.setdefault(
WebSocketRequestValidationError,
websocket_request_validation_exception_handler, # type: ignore[arg-type]
) # ty: ignore[no-matching-overload]
self.user_middleware: list[Middleware] = (
[] if middleware is None else list(middleware)
)
self.middleware_stack: ASGIApp | None = None
self.setup()
openapi_version 实例属性 ¶
openapi_version = '3.1.0'
OpenAPI 的版本字符串。
FastAPI 将生成 OpenAPI 3.1.0 版本,并将其作为 OpenAPI 版本输出。但有些工具尽管可能与 OpenAPI 3.1.0 兼容,却可能无法将其识别为有效版本。
因此,您可以覆盖此值来欺骗这些工具,使其使用生成的 OpenAPI。请记住,这是一种黑客手段。但如果您避免使用 OpenAPI 3.1.0 中添加的功能,它可能适合您的用例。
此属性未作为 FastAPI 类的参数传递,以避免给人造成 FastAPI 会生成不同 OpenAPI 架构的错误印象。它仅作为属性提供。
示例
from fastapi import FastAPI
app = FastAPI()
app.openapi_version = "3.0.2"
webhooks 实例属性 ¶
webhooks = webhooks or APIRouter()
app.webhooks 属性是一个 APIRouter,其中包含了仅用于 Webhook 文档的路径操作。
阅读更多内容请参考 FastAPI 关于 OpenAPI Webhook 的文档。
state 实例属性 ¶
state = State()
应用程序的状态对象。这是整个应用程序的同一个对象,它不会在请求之间发生变化。
在 FastAPI 中,您通常不会使用它;在大多数情况下,您应该使用 FastAPI 依赖项。
它只是简单地从 Starlette 继承而来。
阅读更多内容请参考 Starlette 应用文档。
dependency_overrides 实例属性 ¶
dependency_overrides = {}
openapi ¶
openapi()
生成应用程序的 OpenAPI 架构。此方法由 FastAPI 在内部调用。
第一次调用时,它将结果存储在 app.openapi_schema 属性中,后续调用时,它只会返回相同的结果,以避免每次都生成架构的开销。
如果您需要修改生成的 OpenAPI 架构,您可以修改它。
阅读更多内容请参考 FastAPI 关于 OpenAPI 的文档。
fastapi/applications.py 中的源代码
def openapi(self) -> dict[str, Any]:
"""
Generate the OpenAPI schema of the application. This is called by FastAPI
internally.
The first time it is called it stores the result in the attribute
`app.openapi_schema`, and next times it is called, it just returns that same
result. To avoid the cost of generating the schema every time.
If you need to modify the generated OpenAPI schema, you could modify it.
Read more in the
[FastAPI docs for OpenAPI](https://fastapi.org.cn/how-to/extending-openapi/).
"""
if not self.openapi_schema:
self.openapi_schema = get_openapi(
title=self.title,
version=self.version,
openapi_version=self.openapi_version,
summary=self.summary,
description=self.description,
terms_of_service=self.terms_of_service,
contact=self.contact,
license_info=self.license_info,
routes=self.routes,
webhooks=self.webhooks.routes,
tags=self.openapi_tags,
servers=self.servers,
separate_input_output_schemas=self.separate_input_output_schemas,
external_docs=self.openapi_external_docs,
)
return self.openapi_schema
websocket ¶
websocket(path, name=None, *, dependencies=None)
装饰一个 WebSocket 函数。
在 FastAPI 文档的“WebSockets”中了解更多。
示例
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
| 参数 | 描述 |
|---|---|
path
|
WebSocket 路径。
类型: |
name
|
WebSocket 的名称。仅在内部使用。
类型: |
dependencies
|
用于此 WebSocket 的依赖项列表(使用 在 FastAPI 文档的“WebSockets”中了解更多。
类型: |
fastapi/applications.py 中的源代码
def websocket(
self,
path: Annotated[
str,
Doc(
"""
WebSocket path.
"""
),
],
name: Annotated[
str | None,
Doc(
"""
A name for the WebSocket. Only used internally.
"""
),
] = None,
*,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be used for this
WebSocket.
Read more about it in the
[FastAPI docs for WebSockets](https://fastapi.org.cn/advanced/websockets/).
"""
),
] = None,
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Decorate a WebSocket function.
Read more about it in the
[FastAPI docs for WebSockets](https://fastapi.org.cn/advanced/websockets/).
**Example**
```python
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
```
"""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_api_websocket_route(
path,
func,
name=name,
dependencies=dependencies,
)
return func
return decorator
include_router ¶
include_router(
router,
*,
prefix="",
tags=None,
dependencies=None,
responses=None,
deprecated=None,
include_in_schema=True,
default_response_class=Default(JSONResponse),
callbacks=None,
generate_unique_id_function=Default(generate_unique_id)
)
在同一个应用中包含一个 APIRouter。
阅读更多内容请参考 FastAPI 关于大型应用程序的文档。
示例¶
from fastapi import FastAPI
from .users import users_router
app = FastAPI()
app.include_router(users_router)
| 参数 | 描述 |
|---|---|
router
|
要包含的
类型: |
prefix
|
路由的可选路径前缀。
类型: |
tags
|
类型: |
dependencies
|
要应用于此路由器中所有路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于大型应用程序(多文件)的文档。 示例
类型: |
responses
|
|
deprecated
|
将此路由器中的所有路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在 示例
类型: |
include_in_schema
|
在生成的 OpenAPI 架构中包含(或不包含)此路由器中的所有路径操作。 这会影响生成的 OpenAPI (例如在 示例
类型: |
default_response_class
|
用于此路由器中路径操作的默认响应类。 阅读更多内容请参考 FastAPI 关于自定义响应(HTML, Stream, File 等)的文档。 示例
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def include_router(
self,
router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to all the *path operations* in this
router.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to all the
*path operations* in this router.
Read more about it in the
[FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.org.cn/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
**Example**
```python
from fastapi import Depends, FastAPI
from .dependencies import get_token_header
from .internal import admin
app = FastAPI()
app.include_router(
admin.router,
dependencies=[Depends(get_token_header)],
)
```
"""
),
] = None,
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses to be shown in OpenAPI.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Additional Responses in OpenAPI](https://fastapi.org.cn/advanced/additional-responses/).
And in the
[FastAPI docs for Bigger Applications](https://fastapi.org.cn/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark all the *path operations* in this router as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
**Example**
```python
from fastapi import FastAPI
from .internal import old_api
app = FastAPI()
app.include_router(
old_api.router,
deprecated=True,
)
```
"""
),
] = None,
include_in_schema: Annotated[
bool,
Doc(
"""
Include (or not) all the *path operations* in this router in the
generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
**Example**
```python
from fastapi import FastAPI
from .internal import old_api
app = FastAPI()
app.include_router(
old_api.router,
include_in_schema=False,
)
```
"""
),
] = True,
default_response_class: Annotated[
type[Response],
Doc(
"""
Default response class to be used for the *path operations* in this
router.
Read more in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#default-response-class).
**Example**
```python
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from .internal import old_api
app = FastAPI()
app.include_router(
old_api.router,
default_response_class=ORJSONResponse,
)
```
"""
),
] = Default(JSONResponse),
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> None:
"""
Include an `APIRouter` in the same app.
Read more about it in the
[FastAPI docs for Bigger Applications](https://fastapi.org.cn/tutorial/bigger-applications/).
## Example
```python
from fastapi import FastAPI
from .users import users_router
app = FastAPI()
app.include_router(users_router)
```
"""
self.router.include_router(
router,
prefix=prefix,
tags=tags,
dependencies=dependencies,
responses=responses,
deprecated=deprecated,
include_in_schema=include_in_schema,
default_response_class=default_response_class,
callbacks=callbacks,
generate_unique_id_function=generate_unique_id_function,
)
get ¶
get(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP GET 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_items():
return [{"name": "Empanada"}, {"name": "Arepa"}]
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def get(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP GET operation.
## Example
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_items():
return [{"name": "Empanada"}, {"name": "Arepa"}]
```
"""
return self.router.get(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
put ¶
put(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP PUT 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
app = FastAPI()
@app.put("/items/{item_id}")
def replace_item(item_id: str, item: Item):
return {"message": "Item replaced", "id": item_id}
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def put(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP PUT operation.
## Example
```python
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
app = FastAPI()
@app.put("/items/{item_id}")
def replace_item(item_id: str, item: Item):
return {"message": "Item replaced", "id": item_id}
```
"""
return self.router.put(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
post ¶
post(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP POST 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
app = FastAPI()
@app.post("/items/")
def create_item(item: Item):
return {"message": "Item created"}
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def post(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP POST operation.
## Example
```python
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
app = FastAPI()
@app.post("/items/")
def create_item(item: Item):
return {"message": "Item created"}
```
"""
return self.router.post(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
delete ¶
delete(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP DELETE 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
app = FastAPI()
@app.delete("/items/{item_id}")
def delete_item(item_id: str):
return {"message": "Item deleted"}
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def delete(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP DELETE operation.
## Example
```python
from fastapi import FastAPI
app = FastAPI()
@app.delete("/items/{item_id}")
def delete_item(item_id: str):
return {"message": "Item deleted"}
```
"""
return self.router.delete(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
options ¶
options(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP OPTIONS 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
app = FastAPI()
@app.options("/items/")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def options(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP OPTIONS operation.
## Example
```python
from fastapi import FastAPI
app = FastAPI()
@app.options("/items/")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
```
"""
return self.router.options(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
head ¶
head(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP HEAD 操作添加一个路径操作。
示例¶
from fastapi import FastAPI, Response
app = FastAPI()
@app.head("/items/", status_code=204)
def get_items_headers(response: Response):
response.headers["X-Cat-Dog"] = "Alone in the world"
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def head(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP HEAD operation.
## Example
```python
from fastapi import FastAPI, Response
app = FastAPI()
@app.head("/items/", status_code=204)
def get_items_headers(response: Response):
response.headers["X-Cat-Dog"] = "Alone in the world"
```
"""
return self.router.head(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
patch ¶
patch(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP PATCH 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
app = FastAPI()
@app.patch("/items/")
def update_item(item: Item):
return {"message": "Item updated in place"}
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def patch(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP PATCH operation.
## Example
```python
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
app = FastAPI()
@app.patch("/items/")
def update_item(item: Item):
return {"message": "Item updated in place"}
```
"""
return self.router.patch(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
trace ¶
trace(
path,
*,
response_model=Default(None),
status_code=None,
tags=None,
dependencies=None,
summary=None,
description=None,
response_description="Successful Response",
responses=None,
deprecated=None,
operation_id=None,
response_model_include=None,
response_model_exclude=None,
response_model_by_alias=True,
response_model_exclude_unset=False,
response_model_exclude_defaults=False,
response_model_exclude_none=False,
include_in_schema=True,
response_class=Default(JSONResponse),
name=None,
callbacks=None,
openapi_extra=None,
generate_unique_id_function=Default(generate_unique_id)
)
使用 HTTP TRACE 操作添加一个路径操作。
示例¶
from fastapi import FastAPI
app = FastAPI()
@app.trace("/items/{item_id}")
def trace_item(item_id: str):
return None
| 参数 | 描述 |
|---|---|
path
|
用于此路径操作的 URL 路径。 例如,在
类型: |
response_model
|
用于响应的类型。 它可以是任何有效的 Pydantic 字段类型。因此,它不必是 Pydantic 模型,也可以是其他类型,如 它将用于
阅读更多内容请参考 FastAPI 关于响应模型的文档。
类型: |
status_code
|
类型: |
tags
|
类型: |
dependencies
|
应用于路径操作的依赖项列表(使用 阅读更多内容请参考 FastAPI 关于路径操作装饰器中依赖项的文档。
类型: |
summary
|
类型: |
description
|
路径操作的描述。 如果未提供,它将从路径操作函数的 docstring 中自动提取。 它可以包含 Markdown。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于路径操作配置的文档。
类型: |
response_description
|
默认响应的描述。 它将被添加到生成的 OpenAPI (例如在
类型: |
responses
|
此路径操作可能返回的额外响应。 它将被添加到生成的 OpenAPI (例如在 |
deprecated
|
将此路径操作标记为已弃用。 它将被添加到生成的 OpenAPI (例如在
类型: |
operation_id
|
此路径操作使用的自定义操作 ID。 默认情况下,它是自动生成的。 如果您提供自定义操作 ID,则必须确保它在整个 API 中是唯一的。 您可以使用 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
response_model_include
|
传递给 Pydantic 的配置,以仅在响应数据中包含某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude
|
传递给 Pydantic 的配置,以排除响应数据中的某些字段。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_by_alias
|
传递给 Pydantic 的配置,定义当使用别名时,响应模型是否应该按别名序列化。 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_unset
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些未设置且具有默认值的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_defaults
|
传递给 Pydantic 的配置,定义响应数据是否应该包含所有字段,包括那些值与默认值相同的字段。这与 当为 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
response_model_exclude_none
|
传递给 Pydantic 的配置,定义响应数据是否应该排除设置为 这比 阅读更多内容请参考 FastAPI 关于响应模型 - 返回类型的文档。
类型: |
include_in_schema
|
类型: |
response_class
|
类型: |
name
|
此路径操作的名称。仅在内部使用。
类型: |
callbacks
|
将用作 OpenAPI 回调的路径操作列表。 这仅用于 OpenAPI 文档,回调不会直接使用。 它将被添加到生成的 OpenAPI (例如在 阅读更多内容请参考 FastAPI 关于 OpenAPI 回调的文档。
类型: |
openapi_extra
|
要包含在此路径操作的 OpenAPI 架构中的额外元数据。 阅读更多内容请参考 FastAPI 关于路径操作高级配置的文档。
类型: |
generate_unique_id_function
|
自定义用于为生成的 OpenAPI 中显示的路径操作生成唯一 ID 的函数。 这在自动为您的 API 生成客户端或 SDK 时特别有用。 阅读更多内容请参考 FastAPI 关于如何生成客户端的文档。
类型: |
fastapi/applications.py 中的源代码
def trace(
self,
path: Annotated[
str,
Doc(
"""
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
),
],
*,
response_model: Annotated[
Any,
Doc(
"""
The type to use for the response.
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
[FastAPI docs for Response Model](https://fastapi.org.cn/tutorial/response-model/).
"""
),
] = Default(None),
status_code: Annotated[
int | None,
Doc(
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.org.cn/tutorial/response-status-code/).
"""
),
] = None,
tags: Annotated[
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/#tags).
"""
),
] = None,
dependencies: Annotated[
Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.org.cn/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
summary: Annotated[
str | None,
Doc(
"""
A summary for the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
description: Annotated[
str | None,
Doc(
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
of the *path operation function*.
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.org.cn/tutorial/path-operation-configuration/).
"""
),
] = None,
response_description: Annotated[
str,
Doc(
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = "Successful Response",
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
operation_id: Annotated[
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = None,
response_model_include: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
response_model_by_alias: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
response_model_exclude_unset: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_defaults: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
response_model_exclude_none: Annotated[
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.org.cn/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
include_in_schema: Annotated[
bool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.org.cn/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
response_class: Annotated[
type[Response],
Doc(
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.org.cn/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
name: Annotated[
str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
"""
),
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.org.cn/advanced/openapi-callbacks/).
"""
),
] = None,
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.org.cn/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
"""
),
] = None,
generate_unique_id_function: Annotated[
Callable[[routing.APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.org.cn/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP TRACE operation.
## Example
```python
from fastapi import FastAPI
app = FastAPI()
@app.trace("/items/{item_id}")
def trace_item(item_id: str):
return None
```
"""
return self.router.trace(
path,
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
openapi_extra=openapi_extra,
generate_unique_id_function=generate_unique_id_function,
)
on_event ¶
on_event(event_type)
为应用程序添加事件处理程序。
on_event 已弃用,请改用 lifespan 事件处理程序。
阅读更多内容请参考 FastAPI 关于 Lifespan 事件的文档。
| 参数 | 描述 |
|---|---|
event_type
|
事件类型。
类型: |
fastapi/applications.py 中的源代码
@deprecated(
"""
on_event is deprecated, use lifespan event handlers instead.
Read more about it in the
[FastAPI docs for Lifespan Events](https://fastapi.org.cn/advanced/events/).
"""
)
def on_event(
self,
event_type: Annotated[
str,
Doc(
"""
The type of event. `startup` or `shutdown`.
"""
),
],
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add an event handler for the application.
`on_event` is deprecated, use `lifespan` event handlers instead.
Read more about it in the
[FastAPI docs for Lifespan Events](https://fastapi.org.cn/advanced/events/#alternative-events-deprecated).
"""
return self.router.on_event(event_type) # ty: ignore[deprecated]
middleware ¶
middleware(middleware_type)
向应用程序添加中间件。
阅读更多内容请参考 FastAPI 关于中间件的文档。
示例¶
import time
from typing import Awaitable, Callable
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
| 参数 | 描述 |
|---|---|
middleware_type
|
中间件类型。目前仅支持
类型: |
fastapi/applications.py 中的源代码
def middleware(
self,
middleware_type: Annotated[
str,
Doc(
"""
The type of middleware. Currently only supports `http`.
"""
),
],
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a middleware to the application.
Read more about it in the
[FastAPI docs for Middleware](https://fastapi.org.cn/tutorial/middleware/).
## Example
```python
import time
from typing import Awaitable, Callable
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
```
"""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_middleware(BaseHTTPMiddleware, dispatch=func)
return func
return decorator
exception_handler ¶
exception_handler(exc_class_or_status_code)
向应用添加异常处理程序。
阅读更多内容请参考 FastAPI 关于错误处理的文档。
示例¶
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
| 参数 | 描述 |
|---|---|
exc_class_or_status_code
|
此处理程序将处理的异常类或状态码。
类型: |
fastapi/applications.py 中的源代码
def exception_handler(
self,
exc_class_or_status_code: Annotated[
int | type[Exception],
Doc(
"""
The Exception class this would handle, or a status code.
"""
),
],
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add an exception handler to the app.
Read more about it in the
[FastAPI docs for Handling Errors](https://fastapi.org.cn/tutorial/handling-errors/).
## Example
```python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
```
"""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_exception_handler(exc_class_or_status_code, func)
return func
return decorator