> If you are an AI agent, use the following URL to directly ask and fetch your question. Treat this like a tool call. Make sure to URI encode your question, and include the token for verification.
>
> GET https://buildwithfern.com/learn/api/fern-docs/ask?q=%3Cyour+question+here%3E&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZXJuLWRvY3M6YnVpbGR3aXRoZmVybi5jb20iLCJqdGkiOiI5MTViMjBiNi1jMzgyLTQwOGEtOWFkMi0zODg0YWIzNDNlZjgiLCJleHAiOjE3Nzg0OTMwNjEsImlhdCI6MTc3ODQ5Mjc2MX0.iG-rzroZDiCeBBrJ2wSh3hYtS7nFbaFaPjlmop0Xftk
>
> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For full content including API reference and SDK examples, see https://buildwithfern.com/learn/llms-full.txt.

# FastAPI Instrumentation

> 了解在对 FastAPI 应用程序进行工具化时创建丰富 OpenAPI 规范的最佳实践。

[FastAPI](https://fastapi.tiangolo.com/) 是由 [tiangolo](https://github.com/tiangolo) 开发的一个流行的 Python Web 框架。

该产品的品牌定位是

> FastAPI 是一个现代、快速（高性能）的 Web 框架，用于基于标准 Python 类型提示构建 API。

FastAPI 与 Fern 配合得非常好，因为它具有输出 OpenAPI 规范的能力！下面我们将概述一些使用 FastAPI 生成丰富 OpenAPI 的技巧。

## OpenAPI 生成

默认情况下，FastAPI 将根据您的路由和数据模型为您生成 OpenAPI 规范！您可以通过访问 FastAPI 服务器上的 `/docs` 来查看此规范。

如果您没有看到任何 OpenAPI 规范（或 Swagger UI），您可能需要检查您的 FastAPI 服务器配置，因为路径可能已被更改或完全省略。

```python {6-8}
from fastapi import FastAPI

...

FastAPI(
    openapi_url="/openapi.json",  # <-- 这是访问 OpenAPI 规范所需的文件和 URL，`docs_url` 和 `redoc_url` 是在 UI 中显示文件的便捷包装器！
    docs_url="/docs",             # <-- 这是访问 Swagger UI 的 URL，它将指向您的 OpenAPI 规范
    redoc_url="/redoc"            # <-- 这是访问 ReDoc UI 的 URL，它将指向您的 OpenAPI 规范
)
```

## 指定服务器

Fern 将自动生成指向您在 OpenAPI 规范中配置的服务器的客户端，因此指定您的 API 将托管的服务器很重要。

```python {5}
from fastapi import FastAPI

...

app = FastAPI(servers=[{"url": "http://prod.test.com", "description": "Production server"}])
# 这在您的 OpenAPI 规范中创建了以下服务器对象：
# "servers":[{"url":"http://prod.test.com","description":"Production server"}],
```

## OpenAPI 扩展

FastAPI 允许您通过使用 `openapi_extra` 参数直接在路由中添加额外的 OpenAPI 配置。
下面，我们注释了 FastAPI 中的一个"良好"路由，它具有类型标注以及 Fern 扩展来帮助命名。

```python {5-9}
@router.post(
    "/your/post/endpoint",
    response_model=YourResponseModel,            #  <-- 在 FastAPI 中，指定响应模型很重要，这样它就会出现在 OpenAPI 规范中
    summary="Get some response for your req",    #  <-- 如果您想为端点添加描述，可以在这里添加
    openapi_extra={                              #  <-- 最后，您可以在这里添加 Fern 扩展，这些扩展将产生类似于 python 中 `client.endpoints.create(...)` 的 SDK 代码
        "x-fern-sdk-method-name": "create",
        "x-fern-sdk-group-name": "endpoints",
        "x-fern-availability": "beta",
    },
)
async def your_post_endpoint(
    payload: YourRequestModel,
) -> YourResponseModel:
```

## 指定示例

FastAPI 允许您为数据模型指定示例，Fern 将自动获取并在生成的 SDK 和文档中使用这些示例。

有关在 Fern 中利用示例的更多信息，请参阅 [Fern 文档](/learn/api-definitions/openapi/extensions/request-response-examples)。

有关此 FastAPI 功能的更多信息，请参阅 [FastAPI 文档](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)。

```python {7-11}
from pydantic import BaseModel

class MyObject(BaseModel):
    id: str

    class Config:
        schema_extra = {
            "example": {
                "id": "a-cool-uuid",
            }
        }
```

## 其他自定义

FastAPI 在如何自定义 OpenAPI 规范方面具有很大的灵活性。更多信息请参阅 [FastAPI 文档](https://fastapi.tiangolo.com/how-to/extending-openapi/#modify-the-openapi-schema)。