FastAPI で POST の引数の受け取り方です。
サーバープログラム
post01.py
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
aa: float
bb: float
app = FastAPI()
@app.post("/sum/")
async def create_item(item: Item):
rvalue = {}
rvalue["wa"] = item.aa + item.bb
return rvalue
@app.post("/diff/")
async def create_item(item: Item):
rvalue = {}
rvalue["sa"] = item.aa - item.bb
return rvalue
サーバーの起動
uvicorn post01:app --reload
クライアントからアクセス
$ http POST http://127.0.0.1:8000/sum/ aa=12.1 bb=34.5
HTTP/1.1 200 OK
content-length: 11
content-type: application/json
date: Sat, 05 Jun 2021 04:49:11 GMT
server: uvicorn
{
"wa": 46.6
}
$ http POST http://127.0.0.1:8000/diff/ aa=12.1 bb=34.5
HTTP/1.1 200 OK
content-length: 12
content-type: application/json
date: Sat, 05 Jun 2021 04:49:37 GMT
server: uvicorn
{
"sa": -22.4
}
確認したバージョン
$ python
Python 3.12.7 (main, Feb 4 2025, 14:46:03) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fastapi
>>> fastapi.__version__
'0.110.3'