4. FastApi 快速入门

128 阅读2分钟

安装

FastAPI 是为异步编程设计的框架,它支持 异步请求处理并发和高效的 异步 I/O,因此它依赖于 ASGI 协议来提供异步支持。

pip install fastapi
# FastAPI 要运行起来就必须使用asgi 服务器 包括但不限于 uvicorn
pip install uvicorn

快速入门

  1. 创建项目文件夹 例如 fastpi_app

  2. 创建启动文件 例如 main.py

  3. 写入代码 import uvicorn from fastapi import FastAPI app = FastAPI()

    # 通过装饰器 实现路由映射
    @app.get("/")
    async def read_root():
        return {"Hello": "World"}
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
  4. 启动 在终端输入 uvicorn main:app --reload

    uvicorn main:app --reload
        INFO:     Will watch for changes in these directories: ['E:\\fastapi_app']
        INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
        INFO:     Started reloader process [5320] using StatReload
        INFO:     Started server process [3128]
        INFO:     Waiting for application startup.
        INFO:     Application startup complete.   
        INFO:     127.0.0.1:64125 - "GET /items/1 HTTP/1.1" 200 OK
    
  5. 浏览器验证

    image.png

  6. 使用python 命令 启动 python main.py 即可 import uvicorn from fastapi import FastAPI

    app = FastAPI()
    
    # 通过装饰器 实现路由映射
    @app.get("/")
    async def read_root():
        return {"Hello": "World"}
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    
    if __name__ == '__main__':
        uvicorn.run(app)
    
  7. 查看自动化文档 http://127.0.0.1:8000/docs | http://127.0.0.1:8000/openapi.json image.png

    如果是需要对传入的参数 需要增加注释则 可以增加description

    from fastapi import FastAPI, Query, Path, Body
    app = FastAPI()
    
    @app.get("/items/{item_id}")
    async def read_item(
        item_id: int = Path(..., description="传入的item_id"),
        q: str = Query(None, description="Optional search query to filter items")
    ):
        return {"item_id": item_id, "q": q}
    
    @app.post("/items/")
    async def create_item(
        item: dict = Body(..., description="The item details to be created")
    ):
        return {"item": item}
    

    image.png

    如果是要对返回的参数 需要增加注释则 可以

    from fastapi import FastAPI
    from pydantic import BaseModel, Field
    
    app = FastAPI()
    
    # 定义响应模型,使用 Field 来为字段添加描述
    class ItemResponse(BaseModel):
        item_id: int = Field(..., description="The unique ID of the item")
        name: str = Field(..., description="The name of the item")
        description: str = Field(None, description="A brief description of the item")
    
    @app.get("/items/{item_id}", response_model=ItemResponse)
    async def read_item(item_id: int):
        # 返回一些假数据
        return {"item_id": item_id, "name": "Item Name", "description": "Item Description"}
    

    image.png

  8. 可以讲http://127.0.0.1:8000/openapi.json 下载 导入到postman 中方便后续测试