0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FastAPIでPythonコードをWeb APIにラップする手順(ローカル環境編)

0
Posted at

本記事では、MacBook Pro上でPythonコードをFastAPIを使ってHTTP APIとしてラップする手順を解説します。
概ねgpt4にて記事執筆しました。

📦 環境

  • macOS(MacBook Pro)
  • Python 3.9 以上
  • 仮想環境(venv)
  • FastAPI / Uvicorn

🧭 手順

① プロジェクトディレクトリ作成

mkdir python-api && cd python-api

② 仮想環境を作成して有効化

python3 -m venv wrapenv
source wrapenv/bin/activate

③ 必要なライブラリをインストール

pip install fastapi uvicorn
  • ライブラリの説明

    • FastAPI
      PythonでAPIを簡単に作成できるWebフレームワーク。自動でOpenAPIドキュメントが生成され、型ヒントを活かしたバリデーションや補完が強力。

    • Uvicorn
      FastAPIアプリケーションを実行するためのASGI(非同期サーバーゲートウェイインターフェース)サーバー。軽量で高速、--reload オプションでコード変更時に自動リロードも可能。

main.py を作成

# main.py
from fastapi import FastAPI

# FastAPIアプリの初期化
app = FastAPI()

# 内部処理にする関数(実際の業務ロジックに相当)
def hello_world(name: str) -> str:
    return f"Hello, {name}!"

# ルート:GET /hello?name=Eriko のようにアクセス
@app.get("/hello")
def read_root(name: str = "World"):
    return {"message": hello_world(name)}

⑤ 起動コマンド(ローカルテスト)

uvicorn main:app --reload

📝 Gitで管理

git init
echo "venv/" >> .gitignore
git add .
git commit -m "Initial FastAPI app"

✅ 結果

FastAPIで定義した関数がローカル環境でHTTP APIとして正常に動作しました。

思っていたよりもセットアップが簡単で、短時間でAPIを立ち上げることができました。特に uvicorn を使ったローカル実行の手軽さと、FastAPIが自動生成してくれる /docs ページ(Swagger UI)の便利さに驚きました!動くと楽しいので、エラーが起きても手順が分からなくても色々教わりながら試すことができる、gpt4とwarpに感謝。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?