グローバル依存関係とサブ依存関係
アプリ全体またはルーター全体に依存関係を適用し、サブ依存関係を連鎖させます。リクエスト内で依存関係の結果をキャッシュし、整理された階層的なFastAPIアプリケーションを構築します。
「グローバル依存関係とサブ依存関係」はCoddyKit上の無料FastAPI Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはFastAPI Backend Development Bootcamp学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Scaling Up Dependencies
You can attach a dependency to a single route, but real apps need to apply checks broadly. FastAPI supports dependencies at the app, router, and route levels, plus dependencies that depend on other dependencies.
App-Level Dependencies
Pass dependencies=[...] to the FastAPI constructor to run them for every request. Useful for global logging or API-key checks.
from fastapi import FastAPI, Depends
async def verify_key():
...
app = FastAPI(dependencies=[Depends(verify_key)])Router-Level Dependencies
Attach dependencies to an APIRouter so they apply to every route in that router but not the whole app.
from fastapi import APIRouter, Depends
admin = APIRouter(
prefix='/admin',
dependencies=[Depends(verify_admin)],
)Dependencies Without a Return
When you only need a side effect (like raising on failure), put the dependency in the dependencies list rather than a parameter. Its return value is ignored.
@app.get('/secure', dependencies=[Depends(verify_key)])
async def secure():
return {'ok': True}Sub-Dependencies
A dependency can itself depend on another dependency. FastAPI resolves the whole chain automatically.
def get_token(authorization: str = Header(None)):
return authorization
def get_user(token: str = Depends(get_token)):
return lookup_user(token)
@app.get('/me')
async def me(user = Depends(get_user)):
return userWhy Layer Dependencies
Sub-dependencies let you compose small, single-purpose pieces: parse the token, then resolve the user, then check permissions. Each layer is reusable and independently testable.
Dependency Caching
Within a single request, FastAPI caches each dependency by default. If two dependencies both need get_user, it runs only once. Disable with Depends(fn, use_cache=False).
@app.get('/data')
async def data(
a = Depends(get_user),
b = Depends(get_user), # reuses cached result
):
return a is bModeling the Resolution Chain
The resolver walks dependencies depth-first and caches by function. Here is a simplified version in plain Python.
cache = {}
calls = []
def resolve(name):
if name in cache:
return cache[name]
calls.append(name)
cache[name] = name + '_value'
return cache[name]
resolve('get_user'); resolve('get_user'); resolve('get_token')
print(calls)Combining Levels
Precedence flows from broad to narrow: app dependencies run first, then router, then route. A request to a router route runs all three layers in order.
Overriding for Tests
Swap any dependency in tests with app.dependency_overrides to inject fakes without touching production code.
app.dependency_overrides[get_user] = lambda: {'id': 1, 'name': 'Test'}Best Practices
Keep dependencies focused:
- One responsibility per dependency.
- Use app/router level for cross-cutting concerns.
- Rely on caching; only disable it when you truly need fresh evaluation.
Quick Check
Two parameters in the same route both use Depends(get_user) with default settings. How many times does get_user run for one request?
Recap
You leveled up dependency injection:
- Applied dependencies at app, router, and route scope.
- Used side-effect-only dependencies in the
dependencieslist. - Chained sub-dependencies and relied on per-request caching.
- Overrode dependencies for testing.
よくある質問
「グローバル依存関係とサブ依存関係」レッスンは無料ですか?
はい。「グローバル依存関係とサブ依存関係」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、FastAPI Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。
「グローバル依存関係とサブ依存関係」で何を学びますか?
アプリ全体またはルーター全体に依存関係を適用し、サブ依存関係を連鎖させます。リクエスト内で依存関係の結果をキャッシュし、整理された階層的なFastAPIアプリケーションを構築します。 ブラウザで直接実行するハンズオンコードでFastAPI Backend Development Bootcampを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
FastAPI Backend Development Bootcampを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのFastAPI Backend Development Bootcampは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「グローバル依存関係とサブ依存関係」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このFastAPI Backend Development Bootcampレッスンでコードを書いて実行できますか?
はい。すべてのFastAPI Backend Development Bootcampレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- FastAPIの依存関係を理解する
- 共通の依存関係を注入する
- クラスベースの依存関係とyield依存関係
- グローバル依存関係とサブ依存関係