Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

FastAPI

最終更新 Markdown で表示Agent セットアップ

Python Workers では FastAPI ↗ を使えます。

FastAPI アプリケーションは Asynchronous Server Gateway Interface(ASGI) ↗ というプロトコルを使います。 そのため FastAPI 自身はソケットの読み書きをしません。ASGI アプリケーションは ASGI サーバーに接続されることを想定しています。 よく使うのは uvicorn ↗ です。 ASGI サーバーが、アプリケーションに代わって生のソケットをすべて扱います。

Python Workers は、Python Worker から直接使える ASGI サーバー ↗ を提供します。これにより Python Workers で FastAPI を使えます。

クイックスタート

Python Workers で FastAPI を始める手順は次のとおりです。

  1. FastAPI アプリケーションを src/main.py に作成します。
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

from workers import asgi
Default = asgi.entrypoint(app)
  1. Worker を設定する wrangler.jsonc ファイルを作成します。
{
    "$schema": "node_modules/wrangler/config-schema.json",
	"name": "my-fastapi-app",
	"main": "src/main.py",
	// Set this to today's date
	"compatibility_date": "2026-11-14",
	"compatibility_flags": ["python_workers"],
}
"$schema" = "node_modules/wrangler/config-schema.json"
name = "my-fastapi-app"
main = "src/main.py"
# Set this to today's date
compatibility_date = "2026-11-14"
compatibility_flags = [ "python_workers" ]
  1. 依存関係を管理する pyproject.toml ファイルを作成します。
[project]
name = "my-fastapi-app"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
    "fastapi",
]

[dependency-groups]
dev = [
    "workers-py",
    "workers-runtime-sdk"
]
  1. Worker をローカルで実行します。
uv run pywrangler dev
  1. 別のターミナルで、Worker にリクエストを送ります。

    curl http://localhost:8787/

    Worker は次を返します。

    {"Hello": "World"}

フロントエンドを配信する

Workers Static Assets を使うと、FastAPI バックエンドと一緒に任意の静的フロントエンドを配信できます。

これは FastAPI ネイティブの app.frontend() ↗ メソッドと同等です。静的ビルドディレクトリを優先度の低いルートとして配信し、API のパス操作を先に確認します。違いはファイルの置き場所です。app.frontend() はローカルファイルシステムから読みますが、Workers では静的アセットが ASSETS バインディング経由で Cloudflare のグローバルなアセットストアから配信されます。フロントエンドファイルは Worker 本体にバンドルされないため、バンドルを小さく保てます。

フロントエンドのビルド成果物(HTML、CSS、JavaScript ファイルなど)を ./public/ などのディレクトリに置きます。次に Wrangler ファイルに binding を含み run_worker_first を true にした assets ブロックを設定します。 すべてのリクエストが先に FastAPI Worker に届くので、API ルートが 静的ファイルより優先されます。

FastAPI アプリの末尾に、一致しなかったリクエストをアセットバインディングへプロキシするキャッチオールルートを追加します。

{
	"name": "my-fastapi-app",
	"main": "src/worker.py",
	// Set this to today's date
	"compatibility_date": "2026-11-14",
	"compatibility_flags": ["python_workers"],
	"assets": {
		"directory": "./public/",
		"binding": "ASSETS",
		"run_worker_first": true
	}
}
name = "my-fastapi-app"
main = "src/worker.py"
# Set this to today's date
compatibility_date = "2026-11-14"
compatibility_flags = [ "python_workers" ]

[assets]
directory = "./public/"
binding = "ASSETS"
run_worker_first = true

依存関係を管理する pyproject.toml ファイルも作成してください。

[project]
name = "my-fastapi-app"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
    "fastapi",
]

[dependency-groups]
dev = [
    "workers-py",
    "workers-runtime-sdk"
]

次に Worker を書きます。

src/worker.pypython
from fastapi import FastAPI, Request
from fastapi.responses import Response
from workers import asgi


app = FastAPI()
Default = asgi.entrypoint(app)

@app.get("/api/hello")
async def api_hello():
    return {"message": "Hello from the API"}

# Catch-all: proxy everything else to Workers Static Assets.
# This is the Workers equivalent of app.frontend("/", directory="dist").
@app.get("/{path:path}")
async def frontend(path: str, request: Request):
    env = request.scope["env"]
    asset_url = f"https://assets.local/{path}"
    resp = await env.ASSETS.fetch(asset_url)
    body = await resp.bytes()
    return Response(content=body, status_code=resp.status, headers=resp.headers)

この Worker は uv run pywrangler dev でローカル実行できます。

この構成では、/api/hello へのリクエストは FastAPI が処理し、/index.html やそのほかのパスへのリクエストはアセットバインディング経由で ./public/ ディレクトリから配信されます。

静的アセットの設定の詳細は Workers Static Assets のドキュメント を参照してください。

そのほかの例

cloudflare/python-workers-examples リポジトリをクローンし、そこにある FastAPI の例を実行します。

git clone https://github.com/cloudflare/python-workers-examples
cd python-workers-examples/fastapi
uv run pywrangler dev

役に立ちましたか?