FastAPI Backend Development Bootcamp · Lezione

Dipendenze globali e sotto-dipendenze

Applichi dipendenze a un’intera app o a un router, concateni sotto-dipendenze e memorizzi nella cache i risultati delle dipendenze durante una richiesta per creare applicazioni FastAPI pulite e stratificate.

Lezione 4 di 413 passaggi

Dipendenze globali e sotto-dipendenze è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 user

Why 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 b

Modeling 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 dependencies list.
  • Chained sub-dependencies and relied on per-request caching.
  • Overrode dependencies for testing.
Gratis per iniziare

Impara FastAPI Backend Development Bootcamp con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
21
Lezioni
84

Domande Frequenti

La lezione «Dipendenze globali e sotto-dipendenze» è gratuita?

Sì — il testo completo di «Dipendenze globali e sotto-dipendenze» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.

Cosa imparerò in «Dipendenze globali e sotto-dipendenze»?

Applichi dipendenze a un’intera app o a un router, concateni sotto-dipendenze e memorizzi nella cache i risultati delle dipendenze durante una richiesta per creare applicazioni FastAPI pulite e strat… Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?

Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Dipendenze globali e sotto-dipendenze»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?

Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Comprendere le dipendenze in FastAPI
  2. Iniezione delle dipendenze comuni
  3. Dipendenze basate su classi e yield
  4. Dipendenze globali e sotto-dipendenze
← Torna a FastAPI Backend Development Bootcamp