Python | FastAPIでAPI作成 ~その1:インストール~

Python | FastAPIでAPI作成 ~その1:インストール~

今回は、高速でWebアプリが作成可能な「FastAPI」を検証します。

公式ドキュメントを参考にしています。

今回利用するpythonのバージョンは以下の通りです。

C:\Users\ユーザー>python --version
Python 3.9.7

①pipでinstallする

pipを実行して(1)fastapiと(2)uvicorn をインストールする

pip3 install fastapi
pip3 install uvicorn[standard]

②main.pyを作成する

公式ドキュメントに沿って、main.pyを作成します。以下の様なフォルダ構成にします。

Fast_API_TEST
 └ main.py

main.pyの中身は以下の通り

from fastapi import FastAPI

app = FastAPI() # インスタンスを作成

@app.get("/") # @:デコレータ
async def root():
    return {"message": "Hello World"}

③FastAPIを起動する

コマンドプロンプトにて以下のコマンドを実行します。これにより、クライアントからの問い合わせを受け付ける状態になります。

uvicorn main:app --reload

main → main.pyのこと

app → main.py内の appオブジェクトのこと

以下の様にstartupすれば成功です。

④ブラウザでローカルホストに問い合わせる

今回は、プログラム実行端末自体がサーバとなりますので、ローカルホストに問い合わせます。

http://localhost:8000 または http://127.0.0.1:8000

パスによって表示を変化させる

パスによって表示するものを変えるには以下の通り

http://localhost:8000 → Hello World!

http://localhost:8000/test01 → Test01

http://localhost:8000/test02 → Test02

from fastapi import FastAPI

app = FastAPI() # インスタンスを作成

@app.get("/") # @:デコレータ
async def root():
    return {"message": "Hello World"}

@app.get("/test01")
async def test01():
    return {"message": "Test01"}

@app.get("/test02")
async def test02():
    return {"message": "Test02"}