/ では API ドキュメント (/docs) を開くよう案内し、/hello_world で {"message": "hello world"} を返す FastAPI アプリです。ローカル実行と Docker 実行の 2 パターンを日本語でまとめています。
- プロジェクトへ移動
cd "api_hello_world"
- 仮想環境を作成してアクティベート
python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate
- 依存パッケージをインストール
pip install -r requirements.txt
- 開発サーバーを起動
uvicorn main:app --host 0.0.0.0 --port 8080 # 自動再起動したい場合は --reload を追加 - ブラウザで
http://127.0.0.1:8080/を開き、http://0.0.0.0:8080/docsへの案内が出ることを確認。http://127.0.0.1:8080/hello_worldで{"message":"hello world"}を確認。
- プロジェクトへ移動
cd "api_hello_world"
- コンテナイメージをビルド
docker build -t fastapi-hello . - コンテナを起動(ホストの 8080 に公開)
docker run -p 8080:8080 fastapi-hello
- ブラウザで
http://127.0.0.1:8080/を開き、http://0.0.0.0:8080/docsへの案内が出ることを確認。http://127.0.0.1:8080/hello_worldで{"message":"hello world"}を確認。