1
0

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で始めるDepends入門(共通処理の再利用)

1
Last updated at Posted at 2026-08-31

はじめに

FastAPI最大の特徴の一つがDependsです。
Pydanticと並ぶFastAPIの中核機能です。

認証・DB接続やログ出力などの共通処理を再利用できます。

FastAPIで始めるWeb API開発入門
の第3弾です


Dependsとは

共通処理を自動実行する仕組みです。

from fastapi import Depends

基本形

from fastapi import Depends

def get_message() -> str:
    return "hello"

@app.get("/")
def index(message: str = Depends(get_message)):
    return {"message": message}

実行順

FastAPI

↓

get_message()

↓

index()

JWT認証で利用する

def get_current_user():

    token = "JWT検証"

    return {
        "id": 1,
        "name": "yamada",
        "is_admin": True
    }
@app.get("/profile")
def profile(user: dict = Depends(get_current_user)):
    return user

権限チェック

from fastapi import Depends, HTTPException

def check_admin(user: dict = Depends(get_current_user)) -> dict:
    if not user.get("is_admin"):
        raise HTTPException(
            status_code=403,
            detail="管理者ではありません"
        )
    return user

@app.get("/admin")
def get_admin_data(admin: dict = Depends(check_admin)):
    return {
        "message": "管理者です",
        "admin": admin
    }

複数Depends

def get_db():
    # データベースセッションのモック
    return "db_session"
    
@app.get("/users")
def get_users(
    user: dict = Depends(get_current_user),
    db: str = Depends(get_db)
):
    return {"user": user, "db": db}

実務で多い用途

  • JWT認証
  • 権限管理
  • DB接続
  • ログ出力
  • 共通設定

DependsがFastAPIで重要な理由

FastAPIでは認証・認可・DB管理をほぼDependsで実装します。

Pydanticと並ぶFastAPIの中核機能です。


まとめ

  • 共通処理を再利用できる
  • JWT認証と相性が良い
  • DBセッション管理でよく使う
  • FastAPIらしさの中心となる機能
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?