本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

FastAPI ドキュメント
FastAPI
Getting Started with FastAPIProject StructureCore ConceptsData and StateTestingDeployment
ディスカッション

FastAPI ガイド · 2/6

Project Structure

この章は現在、英語でのみ提供しています。

FastAPI does not impose a folder layout. A single file is a fine place to start, but as endpoints pile up you will want to split them by feature. Based on the "Bigger Applications" example from the official docs, this chapter covers a common layout, routers, configuration files and conventions.

A recommended layout

hello-fastapi/
├── app/
│   ├── __init__.py
│   ├── main.py          # creates FastAPI(), registers routers
│   ├── dependencies.py  # shared dependencies
│   ├── config.py        # settings (pydantic-settings)
│   ├── models.py        # Pydantic and SQLModel models
│   └── routers/
│       ├── __init__.py
│       ├── items.py
│       └── users.py
├── tests/
│   └── test_items.py
├── .env                 # local environment variables (not committed)
├── pyproject.toml       # or requirements.txt
└── Dockerfile

The app folder is a Python package. Every folder gets an __init__.py so imports like from app.routers import items work. Run the dev server with fastapi dev app/main.py; the fastapi command works out the package structure from the file path and finds the app object for you.

Splitting routes with APIRouter

An APIRouter behaves like a small FastAPI app. Create one per feature and give it a shared path prefix and documentation tags in one place.

# app/routers/items.py
from fastapi import APIRouter, HTTPException

router = APIRouter(prefix="/items", tags=["items"])

fake_items = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}


@router.get("/")
def list_items():
    return fake_items


@router.get("/{item_id}")
def read_item(item_id: str):
    if item_id not in fake_items:
        raise HTTPException(status_code=404, detail="Item not found")
    return fake_items[item_id]

main.py then only creates the app and registers routers. The entry point stays short, and each feature's code lives in its own file.

# app/main.py
from fastapi import FastAPI

from app.routers import items, users

app = FastAPI(title="Hello FastAPI", version="0.1.0")

app.include_router(items.router)
app.include_router(users.router)


@app.get("/health")
def health():
    return {"status": "ok"}

include_router also accepts prefix, tags and dependencies, so you can mount the same router under /api/v1, or require authentication for an entire admin router.

A dependencies module

Dependencies shared by several routers belong in dependencies.py. Here is a simple check of a token in a request header:

# app/dependencies.py
from typing import Annotated

from fastapi import Header, HTTPException


async def verify_token(x_token: Annotated[str, Header()]):
    if x_token != "secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")
この章について質問がありますか?
前の章Getting Started with FastAPI次の章Core Concepts

Pass it when creating a router, as in APIRouter(dependencies=[Depends(verify_token)]), and it applies to every route on that router. The parameter name x_token is automatically mapped to the x-token header.

Dependencies and configuration files

Project dependencies usually go in pyproject.toml, which tools such as uv, Poetry and Hatch read to manage the virtual environment. If you only use pip, a requirements.txt is enough.

[project]
name = "hello-fastapi"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
    "fastapi[standard]",
    "sqlmodel",
    "pydantic-settings",
]

[dependency-groups]
dev = ["pytest", "ruff"]

Keep values such as database URLs and secret keys out of the code and pass them in through environment variables or a .env file. Add .env to .gitignore and commit a .env.example listing just the variable names. Chapter 4 shows how to read these settings.

Startup and shutdown

Resources that should be prepared once when the app starts and cleaned up when it stops, such as a connection pool or a machine learning model, are handled with lifespan:

from contextlib import asynccontextmanager

from fastapi import FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI):
    print("starting up")    # open connections, load models
    yield
    print("shutting down")  # release resources


app = FastAPI(lifespan=lifespan)

Code before yield runs before the first request is served; code after it runs when the server stops.

Conventions

TopicConvention
Entry pointthe app variable in app/main.py
Routersone file per feature, router = APIRouter(prefix=..., tags=[...])
Modelsseparate input and output models (ItemCreate, ItemPublic)
Teststests/test_*.py, run with pytest
Secretsenvironment variables or .env, never committed

Summary

  • Start with a single main.py, then move to an app package with a routers folder as it grows.
  • Group routes per feature with APIRouter and register them with app.include_router.
  • Put shared dependencies in dependencies.py and configuration in environment variables or .env.
  • Manage startup and shutdown resources with lifespan.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。