FastAPI環境構築完全ガイド
FastAPI環境構築完全ガイド
Section titled “FastAPI環境構築完全ガイド”FastAPIの環境構築から、実務で使えるベストプラクティスまで詳しく解説します。
1. FastAPIとは
Section titled “1. FastAPIとは”FastAPIの特徴
Section titled “FastAPIの特徴”FastAPIは、PythonのモダンなWebフレームワークです。高いパフォーマンスと開発効率を両立しています。
FastAPIの特徴 ├─ 高速なパフォーマンス(Node.jsやGoに匹敵) ├─ 自動APIドキュメント生成 ├─ 型安全性(Pydantic) └─ 非同期処理のサポートなぜFastAPIが必要か
Section titled “なぜFastAPIが必要か”問題のある構成(FastAPIなし):
# 問題: 低レベルのHTTP処理を手動で実装from http.server import HTTPServer, BaseHTTPRequestHandlerimport json
class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"Hello": "World"}).encode())
# 問題点:# 1. ルーティングの実装が必要# 2. リクエスト/レスポンスの処理が複雑# 3. 型安全性がない# 4. APIドキュメントの生成が必要解決: FastAPIによる高速なAPI開発
# 解決: FastAPIがすべてを提供from fastapi import FastAPI
app = FastAPI()
@app.get("/")def read_root(): return {"Hello": "World"}
# メリット:# 1. 自動ルーティング# 2. 自動APIドキュメント生成# 3. 型安全性# 4. 高速なパフォーマンス2. Pythonのインストール
Section titled “2. Pythonのインストール”Pythonのバージョン要件
Section titled “Pythonのバージョン要件”FastAPIは、Python 3.8以上をサポートしています。最新の安定版を使用することを推奨します。
# Pythonのバージョン確認python --version# またはpython3 --version
# 推奨: Python 3.11以上pyenvを使用したPythonバージョン管理(推奨)
Section titled “pyenvを使用したPythonバージョン管理(推奨)”# pyenvのインストール(macOS)brew install pyenv
# pyenvのインストール(Linux)curl https://pyenv.run | bash
# Python 3.11のインストールpyenv install 3.11.5
# プロジェクトディレクトリでPythonバージョンを設定pyenv local 3.11.53. 仮想環境の作成
Section titled “3. 仮想環境の作成”仮想環境とは
Section titled “仮想環境とは”仮想環境は、プロジェクトごとに独立したPython環境を作成する仕組みです。
仮想環境の作成
Section titled “仮想環境の作成”# プロジェクトディレクトリの作成mkdir myprojectcd myproject
# 仮想環境の作成python -m venv venv仮想環境の有効化
Section titled “仮想環境の有効化”# macOS / Linuxsource venv/bin/activate
# Windows (コマンドプロンプト)venv\Scripts\activate
# Windows (PowerShell)venv\Scripts\Activate.ps1仮想環境の無効化
Section titled “仮想環境の無効化”deactivate4. FastAPIとUvicornのインストール
Section titled “4. FastAPIとUvicornのインストール”基本的なインストール
Section titled “基本的なインストール”# FastAPIのインストールpip install fastapi
# Uvicornのインストール(標準オプション付き)pip install "uvicorn[standard]"requirements.txtの作成
Section titled “requirements.txtの作成”# requirements.txtの作成pip freeze > requirements.txt
# 他の環境でのインストールpip install -r requirements.txt実務でのベストプラクティス
Section titled “実務でのベストプラクティス”fastapi==0.104.1uvicorn[standard]==0.24.0pydantic==2.5.0pydantic-settings==2.1.0
# requirements/dev.txt-r base.txtpytest==7.4.3pytest-asyncio==0.21.1httpx==0.25.2black==23.11.0flake8==6.1.0mypy==1.7.1
# requirements/prod.txt-r base.txtgunicorn==21.2.05. 基本的なアプリケーションの作成
Section titled “5. 基本的なアプリケーションの作成”最小限のアプリケーション
Section titled “最小限のアプリケーション”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}サーバーの起動
Section titled “サーバーの起動”# 開発サーバーの起動uvicorn main:app --reload
# カスタムホストとポートuvicorn main:app --host 0.0.0.0 --port 8000 --reload
# 本番環境での起動uvicorn main:app --host 0.0.0.0 --port 8000 --workers 46. APIドキュメントの確認
Section titled “6. APIドキュメントの確認”Swagger UI
Section titled “Swagger UI”# サーバー起動後、ブラウザでアクセスhttp://localhost:8000/docs# サーバー起動後、ブラウザでアクセスhttp://localhost:8000/redoc7. 実務でのベストプラクティス
Section titled “7. 実務でのベストプラクティス”パターン1: プロジェクト構造
Section titled “パターン1: プロジェクト構造”myproject/├── app/│ ├── __init__.py│ ├── main.py│ ├── api/│ │ ├── __init__.py│ │ └── v1/│ │ ├── __init__.py│ │ ├── endpoints/│ │ │ ├── __init__.py│ │ │ ├── users.py│ │ │ └── items.py│ │ └── api.py│ ├── core/│ │ ├── __init__.py│ │ ├── config.py│ │ └── security.py│ ├── models/│ │ ├── __init__.py│ │ └── user.py│ ├── schemas/│ │ ├── __init__.py│ │ └── user.py│ └── services/│ ├── __init__.py│ └── user_service.py├── tests/│ ├── __init__.py│ └── test_api.py├── requirements.txt├── .env└── .gitignoreパターン2: 環境変数の管理
Section titled “パターン2: 環境変数の管理”# .envファイルの作成pip install python-dotenvfrom pydantic_settings import BaseSettings
class Settings(BaseSettings): app_name: str = "My FastAPI App" debug: bool = False database_url: str
class Config: env_file = ".env"
settings = Settings()8. よくある問題と解決策
Section titled “8. よくある問題と解決策”問題1: モジュールが見つからない
Section titled “問題1: モジュールが見つからない”原因:
- 仮想環境が有効化されていない
- パッケージがインストールされていない
解決策:
# 仮想環境の確認which python # macOS/Linuxwhere python # Windows
# パッケージの再インストールpip install -r requirements.txt問題2: ポートが既に使用されている
Section titled “問題2: ポートが既に使用されている”原因:
- 他のアプリケーションが同じポートを使用している
解決策:
# 別のポートを使用uvicorn main:app --port 8001
# ポートの使用状況を確認lsof -i :8000 # macOS/Linuxnetstat -ano | findstr :8000 # Windowsこれで、FastAPIの環境構築の基礎知識と実務での使い方を理解できるようになりました。