4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FastAPIで作るWebアプリ - 基本

Last updated at Posted at 2021-10-28

PythonでAsyncioを使った非同期的プログラミングを追求してきた結果、FastAPIにぶつかりました。Python界においてはモダンなWeb Frameworkということで人気のようです。少し調査していきたいと思います。

【過去記事】
Python Asyncio入門
Aiohttpで作るSimple Web Server - Qiita
Starletteで作る Simple Web Server - QIita
FastAPIで作るWebアプリ - 基本
FastAPIで作るWebアプリ - validation
FastAPIで作るWebアプリ - Body validation
FastAPIで作るWebアプリ - Form validation

FastAPI 公式サイト

以下の情報は公式サイトのチュートリアルの最初のステップを短くまとめたものです。

1.ハローワールド

インストールは以下のコマンドだけで行えます。

pip install fastapi[all]

簡単なハローワールドプログラムを示します。

main.py
from fastapi import FastAPI

app = FastAPI() # FastAPIはStarletteを直接継承するクラスです。


@app.get("/")  # デコレーション、パス= /, オペレーション = get
async def root():
    return {"message": "Hello World"} # コンテンツの生成

FastAPIはStarletteを直接継承するクラスです。FastAPIでもStarletteのすべての機能を利用可能です。
「Starletteで作る Simple Web Server」

以下のコマンドでアプリを起動できます。

uvicorn main:app --reload

以下は起動コマンドの説明

  • main: main.pyファイル (Python "module")。
  • app: main.py内部で作られるobject(app = FastAPI()のように記述される)。
  • --reload: コードの変更時にサーバーを再起動させる。開発用。

起動メッセージです

$uvicorn main:app --reload
INFO:     Will watch for changes in these directories: ['C:\\Users\\User\\git\\python\\asyncio\\fastapi']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12544] using watchgod
INFO:     Started server process [12916]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

メッセージに従って、ブラウザで http://localhost:8000 にアクセスすると以下のコンテンツを受け取ります。

{"message": "Hello World"}

対話的APIドキュメント

これまでの操作だけで、以下のようなドキュメントが自動生成されます。Swagger UIで実装されており、RESTful APIの仕様書であり、実際に**Requestを発行することができます。**開発効率に大きく寄与するものです。
http://localhost:8000/docs

image.png

「Try it out」ボタンをクリックすると、以下のように「Execute」ボタンが現れます。

image.png

この場合はパラメータは無いので、そのまま「Execute」ボタンをクリックするとリクエストが発行されます。

image.png

発行されたRequestと結果のResponseが表示されます。とても便利です。次にパラメータを持つRequestについて見たいと思います。

2.パラメータ

つぎにパスパラメータ、クエリパラメータ、リクエストボディの受け取り方と、Swagger UIを使った確認方法を見ていきましょう。

param.py
from fastapi import FastAPI

app = FastAPI()

###############################
### パスパラメータ
###############################
@app.get("/items/{item_id}")
async def read_item(item_id : int):
    return {"item_id": item_id}


###############################
### クエリパラメータ
###############################
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]



###############################
### リクエストボディ
###############################
from typing import Optional
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

@app.post("/items/")
async def create_item(item: Item):
    return item

リクエストボディの場合について補足です。

  • pydantic から BaseModel をインポートします。
  • BaseModel を継承したクラスとしてデータモデル(Class Item)を宣言します

Swagger UIは以下のように表示されます。

image.png

2-1 パスパラメータ

最初のGETを選択します。まだパラメータの入力はできません。「Try it out」ボタンをクリックします。

image.png

この状態で初めてパラメータを入力できます

image.png

パラメータを入力したら、[Execute]ボタンをクリックします。

image.png

発行されたRequestと成功のResponseが表示されます。

それではパラメータに整数ではなく「Foo」という文字列を入力したらどうでしょう?

image.png

どうやらSwagger UIレベルでエラーになり、Requestは発行されないようです。

image.png

2-2. クエリパラメータ

2番目のGETを選択します。

image.png

パラメータにskip=1, limit=30 を指定します。「Execute」ボタンをクリックします。以下の結果が得られます。

image.png

2-3. リクエストボディ

POSTを選びます。リクエストボディを入力します。

image.png

「Execute」ボタンをクリックすると、以下のような結果が得られます。

image.png

Restful APIの開発と確認が非常に簡単に行えることがわかります。

今回は以上です

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?