Python使用FastAPI的Request Body。
環境
- Python 3.13.3
- FastAPI 0.115.12
事前要求
參考「Python FastAPI Hello World」建立FastAPI專案。
安裝Pydantic
在專案根目錄以命令列輸入pdm add pydantic下載並安裝pydantic,為用來定義資料模型(model)的函式庫。
C:\..\demo>pdm add pydantic
Adding packages to default dependencies: pydantic
0:00:01 🔒 Lock successful.
Changes are written to pyproject.toml.
All packages are synced to date, nothing to do.
0:00:00 🎉 All complete! 0/0
主程式
主程式main.py內容修改如下。
main.py
from fastapi import FastAPI
from pydantic import BaseModel
class Employee(BaseModel):
id: int | None = None
name: str
age: int
def __str__(self):
return f'Employee{{id:{self.id},name:{self.name},age:{self.age}}}'
app = FastAPI()
@app.post("/employees/")
async def create_employee(employee: Employee):
print(employee)
return employee
測試
在專案根目錄輸入fastapi dev main.py啟動專案。
瀏覽器url輸入http://127.0.0.1:8000/docs開啟API文件,在[POST|/employees/]的Request Body輸入以下內容並執行。
{
"name": "john",
"age": 33
}
則在Response Body返回以下結果
{
"id": null,
"name": "john",
"age": 33
}
對應的curl命令如下:
curl -X 'POST' \
'http://127.0.0.1:8000/employees/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "john",
"age": 33
}'
沒有留言:
張貼留言