0Pricing
FastAPI Backend Development Bootcamp · Lesson

Global Dependencies and Sub-Dependencies

Apply dependencies across an entire app or router, chain sub-dependencies, and cache dependency results within a request to build clean, layered FastAPI applications.

Global Dependencies and Sub-Dependencies is a free FastAPI Backend Development Bootcamp lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the FastAPI Backend Development Bootcamp learning path, and your progress syncs across the web and the CoddyKit app. The FastAPI Backend Development Bootcamp course includes 4 lessons in total.

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.

Frequently Asked Questions

Is the “Global Dependencies and Sub-Dependencies” lesson free?

Yes — the full text of “Global Dependencies and Sub-Dependencies” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the FastAPI Backend Development Bootcamp course, upgrade to CoddyKit PRO. The FastAPI Backend Development Bootcamp course includes 4 lessons in total.

What will I learn in “Global Dependencies and Sub-Dependencies”?

Apply dependencies across an entire app or router, chain sub-dependencies, and cache dependency results within a request to build clean, layered FastAPI applications. You practise FastAPI Backend Development Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start FastAPI Backend Development Bootcamp?

No prior experience is required. FastAPI Backend Development Bootcamp on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Global Dependencies and Sub-Dependencies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this FastAPI Backend Development Bootcamp lesson?

Yes. Every FastAPI Backend Development Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Understanding Dependencies in FastAPI
  2. Injecting Common Dependencies
  3. Class-based & Yield Dependencies
  4. Global Dependencies and Sub-Dependencies
← Back to FastAPI Backend Development Bootcamp