セットアップ¶
FastAPI をインストールするところからアプリをローカルで起動するまで。
FastAPI のインストール¶
uv コマンドでインストールする。
FastAPI アプリの作成と起動¶
まずは一番シンプルなものを。
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
main.py としてファイルを保存したら、fastapi devコマンドで FastAPI アプリを起動する。
起動できたら下記のような表示になって、ローカルホストからの接続だけを受け付けられるようになる。
開発していく時はこれで十分。
% uv run fastapi dev
FastAPI Starting development server 🚀
Searching for package file structure from directories with __init__.py files
Importing from /Users/alice/code/my-fastapi-app
module 🐍 main.py
code Importing the FastAPI app object from the module with the following code:
from main import app
app Using import string: main:app
server Server started at http://127.0.0.1:8000
server Documentation at http://127.0.0.1:8000/docs
tip Running in development mode, for production use: fastapi run
Logs:
INFO Will watch for changes in these directories: ['/Users/alice/code/my-fastapi-app']
INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO Started reloader process [92543] using WatchFiles
INFO Started server process [92545]
INFO Waiting for application startup.
INFO Application startup complete.
FastAPI アプリが起動したら curl コマンドでレスポンスを確認できるし、 Swagger UI でも確認できる。