python FastAPI を使ってみた
はじめに
高速で有名なpythonのフレームワークのfast apiのチュートリアルをやってみました。
pythonのフレームワークはflaskくらいしか経験なかったんですが、非常に簡単に立ち上げが出来ました。
※公式のチュートリアルに沿って実施しています。
環境
- lenovo Ideapad Duet(Chroome book)
- Debian GNU/Linux 10 (buster)
- python 3.7.3
インストール
以下コマンドでインストールしていきます。
稼働させるにはUvicornもしくはHypercornと呼ばれるASGIサーバーソフトウェアのインストールが必要だそうです。
pip install fastapi
pip install uvicorn[standard]
ここではuvicornを使用します。
エンドポイントの作成
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
アプリケーション起動
uvicorn main:app --reload
http://127.0.0.1:8000/
にアクセス
GET
関数の引数ですが、
アノテーションのURLに{変数名}を指定することでパス内にパラメータを設定することができ、
その他はクエリストリングから取得するようです。
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
POST(PUT)
POST,PUTはリクエストBodyから取得するようです
curl -X POST -H "Content-Type: application/json" -d '{"name":"testItem", "price":"100","is_offer":true}' localhost:8000/items/5
{"item_name":"testItem","item_id":5}
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.post("/items/{item_id}")
def update_item(item_id: int, item: Item):
print(item)
return {"item_name": item.name, "item_id": item_id}
ドキュメント自動生成
swaggerUI,redoc形式のdドキュメントが自動生成されるのが便利ですね。
swagger
/docs
redoc
/redoc
自動生成されるドキュメントはどのようにカスタマイズするのか等は今後記事にできればと思います。
Author And Source
この問題について(python FastAPI を使ってみた), 我々は、より多くの情報をここで見つけました https://qiita.com/ykyk02ma26/items/b2efb49c15fd9c4ce727著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .