1.Python环境与安装

python环境:Python 3.6+

安装FastApi:

pip install --index-url https://pypi.tuna.tsinghua.edu.cn/simple/ fastapi

2.简单应用

from fastapi import FastAPI
import uvicorn

# 创建 FastAPI 实例
app = FastAPI()

# 根路径
@app.get("/")
async def root():
    return {"message": "Hello World"}

# 带路径参数的 GET 请求
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

# 带查询参数的 GET 请求
@app.get("/users/")
async def read_user(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}


def main():
    uvicorn.run(app, host="0.0.0.0", port=8000)
    
# 确保当脚本直接运行时也能执行main函数
if __name__ == "__main__":
    main()

2.1 运行:

python -m main

这样我们就能在127.0.0.1:8000上运行上面的几个路由链接, uvicorn是用于生成端口服务

http://127.0.0.1:8000/

http://127.0.0.1:8000/items/2

http://127.0.0.1:8000/users

2.2 代码解析:

async def read_item(item_id: int):

定义一个异步函数read_item ,表示期望接收一个int型的数据

3.应用添加数据模型验证

from fastapi import FastAPI
from pydantic import BaseModel,ValidationError
from typing import Optional
import uvicorn

app = FastAPI()

# 定义数据模型
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


# POST 请求根目录
@app.post("/")
async def root(item: Item):
    item = item.dict()
    return item
# POST 请求创建项目
@app.post("/items/")
async def create_item(item: dict):
    try:
        #item = item.dict()
        if item.get('tax') is None: #用get即使不存在tax这个字段,也不会报错。类似php的isset
            return {"error":'tax is require'}
        if item['tax']:
            price_with_tax = item['price'] + item['tax']
            item.update({"price_with_tax": price_with_tax})
        return item
    except Exception  as e:
        print(item)
        return str(e)

# PUT 请求更新项目
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}

def main():
    uvicorn.run(app, host="0.0.0.0", port=8000)
    
# 确保当脚本直接运行时也能执行main函数
if __name__ == "__main__":
    main()

3.1 运行

同上

3.2 代码解析

class Item(BaseModel):

    name: str

    description: Optional[str] = None

    price: float

    tax: Optional[float] = None

定义一个数据模型,指定数据的类型

async def root(item: Item):
    item = item.dict() #转为字典
    return item

期望接收一个Item类的实例,存入时由于Item类继承BaseModel,会自动验证数据,如果数据不符合预期,会弹出下面这样的提示。比如我这里没有传price,而数据模型并不允许none:

{
    "detail": [
        {
            "type": "missing",
            "loc": [
                "body",
                "price"
            ],
            "msg": "Field required",
            "input": {
                "name": "1",
                "description": "1"
            }
        }
    ]
}

async def create_item(item: dict):

表示期望接收一个字典型型的数据 , 如果用api测试工具,一般body的传值方式为json

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐