FastAPI 构建 API 接口

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,基于 Python 类型提示。以下是 FastAPI 请求接口开发的一些规则:

1、路径操作函数

  • 定义路径:使用装饰器(如 @app.get@app.post 等)定义 API 路径和 HTTP 方法。

  • 路径参数:可以包含动态路径参数,通过函数参数接收。
    @app.get("/items/{item_id}")
    async def read_item(item_id: int):
        return {"item_id": item_id}
    
  • 响应模型:指定响应模型,用于定义返回数据的结构和类型。
    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        description: str | None = None
    
    @app.post("/items/", response_model=Item)
    async def create_item(item: Item):
        return item
    

2、请求体和响应模型

  • 请求体:使用 Pydantic 模型(继承自 BaseModel)来定义请求体的结构和验证。
    @app.post("/items/")
    async def create_item(item: Item):
        return item
    
  • 响应模型:定义返回的数据结构,确保返回的数据格式正确。
    @app.get("/items/{item_id}", response_model=Item)
    async def read_item(item_id: int):
        fake_items_db = {"1": {"name": "Foo", "description": "There goes my hero"}}
        return fake_items_db.get(str(item_id))
    

3、依赖注入系统

  • 定义依赖:可以定义依赖函数,用于在请求处理之前执行一些逻辑。
    async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
        return {"q": q, "skip": skip, "limit": limit}
    
    @app.get("/items/")
    async def read_items(commons: dict = Depends(common_parameters)):
        return commons
    
    @app.get("/users/")
    async def read_users(commons: dict = Depends(common_parameters)):
        return commons
    

4、数据验证和转换

  • 类型提示:使用 Python 类型提示来定义参数和模型的类型,FastAPI 会自动进行验证和转换。

  • 错误处理:如果数据不符合定义的类型或约束,FastAPI 会自动生成错误响应。

5、中间件

  • 添加中间件:可以在请求处理前或后执行一些逻辑,如认证、日志记录等。
    from fastapi.middleware.trustedhost import TrustedHostMiddleware
    
    app.add_middleware(
        TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"]
    )
    

6、异常处理

  • 异常类:可以自定义异常类,并使用异常处理器来处理它们。
    from fastapi import FastAPI, HTTPException
    
    app = FastAPI()
    
    items = {"foo": "The Foo Wrestlers"}
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: str):
        if item_id not in items:
            raise HTTPException(status_code=404, detail="Item not found")
        return {"item": items[item_id]}
    

7、异步支持

  • 异步函数:支持异步函数(使用 async def),可以处理异步操作,如数据库访问、网络请求等。
    @app.get("/items/{item_id}")
    async def read_item(item_id: int):
        await some_async_operation()
        return {"item_id": item_id}
    

8、文档自动生成

  • 自动文档:FastAPI 自动生成交互式 API 文档,可以通过 /docs/redoc 访问。

  • 文档注释:可以在代码中添加注释,用于生成更详细的文档。

9、路径操作函数的顺序

  • 匹配顺序:路径操作函数的顺序很重要,先匹配的路径会优先处理。
    @app.get("/users/{user_id}")
    async def read_user(user_id: str):
        # ...
    
    @app.get("/users/me")
    async def read_user_me():
        # ...
    
  • 在上面的例子中,/users/me 应该在 /users/{user_id} 之前定义,否则 /users/me 会被当作 /users/{user_id} 处理。

10、文件上传

  • 文件参数:可以使用 File 参数来接收上传的文件。
    from fastapi import File, UploadFile
    
    @app.post("/files/")
    async def create_file(file: bytes = File(...)):
        return {"file_size": len(file)}
    

11、表单数据

  • 表单参数:可以使用 Form 参数来接收表单数据。
    from fastapi import Form
    
    @app.post("/login/")
    async def login(username: str = Form(...), password: str = Form(...)):
        return {"username": username}
    

12、响应状态码

  • 指定状态码:可以指定自定义的 HTTP 状态码。
    @app.post("/items/", status_code=201)
    async def create_item(name: str):
        return {"name": name}
    

13、背景任务

  • 后台任务:可以在请求处理完成后执行一些后台任务。
    from fastapi import BackgroundTasks
    
    def write_log(message: str):
        with open("log.txt", mode="a") as log_file:
            log_file.write(message + "\n")
    
    @app.post("/send-notification/{email}")
    async def send_notification(email: str, background_tasks: BackgroundTasks):
        background_tasks.add_task(write_log, f"Notification sent to {email}")
        return {"message": "Notification sent in the background"}
    

14、请求头和 cookie

  • 请求头和 cookie 参数:可以从请求头和 cookie 中获取参数。
    from fastapi import Header, Cookie
    
    @app.get("/items/")
    async def read_items(user_agent: str = Header(...), ads_id: str | None = Cookie(None)):
        return {"User-Agent": user_agent, "Ads-ID": ads_id}
    

15、测试

  • 测试客户端:FastAPI 提供了一个测试客户端,可以方便地测试 API。
    from fastapi.testclient import TestClient
    
    client = TestClient(app)
    
    def test_read_main():
        response = client.get("/")
        assert response.status_code == 200
        assert response.json() == {"message": "Hello World"}
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值