1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FastAPI: POST の引数の処理

Last updated at Posted at 2021-06-05

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'
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?