FastAPI 请求模型及校验

  • 什么是请求体:请求体是客户端发送给 API 的数据。不能使用 GET 操作(HTTP 方法)发送请求体。

# coding: utf8


from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

class UserIn(BaseModel):
    name: str
    age: int
    desc: Optional[str] = None    # 可选

@app.post('/users/')
def create_item(user: UserIn):
    return user

# 启动: uvicorn main:app --reload
curl -H "Content-Type: application/json" \
-X POST \
-d '{"name": "tom", "age": 18}' \
127.0.0.1:8000/users/

{"name":"tom","age":18,"desc":null}

Last updated