Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI Dependency Injection

FastAPI Dependency Injection

FastAPI provides a powerful and concise dependency injection system.

Dependency injection is a design pattern that lets you extract common logic (such as database connections, authentication, parameter validation, etc.) into reusable components, then use them in routes as needed.


What is dependency injection

Simply put,Depends onis a function that can use the same parameters as a path operation function (query parameters, path parameters, request body, etc.). FastAPI automatically calls the dependency function before executing the route function and passes its return value to the route function.

Example

from

typing

import

Annotated

from

fastapi

import

Depends

,

FastAPI

app

=

FastAPI

(

)

1. Define the dependency function

def

common_parameters

(

q:

str

|

None

=

None

,

skip:

int

=

0

,

limit:

int

=

100

)

:

   

return

{

"q"

: q

,

"skip"

: skip

,

"limit"

: limit

}

2. Use the dependency in a route

@

app.

get

(

"/items/"

)

async

def

read_items

(

commons:

dict

=

Depends

(

common_parameters

)

)

:

   

commons receives the return value of the dependency function

   

return

commons

@

app.

get

(

"/users/"

)

async

def

read_users

(

commons:

dict

=

Depends

(

common_parameters

)

)

:

   

Multiple routes can reuse the same dependency

   

return

commons

Code explanation:

Section Description
common_parameters Dependency function that handles common query parameters
Depends(common_parameters) Declare parameters commons whose value comes from the dependency function
commons: dict Receives the dictionary returned by the dependency function

Dependency functions and path operation functions use the same way of declaring parameters, and FastAPI automatically resolves the dependency function's parameters. This means dependency functions can also use query parameters, path parameters, request bodies, etc.


Dependency execution flow

When a request arrives, FastAPI's processing order:

  1. Identify the route function and its dependencies
  2. Execute the dependency functions (in dependency order)
  3. Pass the dependency functions' return values to the route function
  4. Execute the route function

Classes as dependencies

Besides functions, you can also use classes as dependencies:

Example

from

typing

import

Annotated

from

fastapi

import

Depends

,

FastAPI

app

=

FastAPI

(

)

Declare a dependency with a class

class

CommonQueryParams:

   

def

init

(

self

,

q:

str

|

None

=

None

,

skip:

int

=

0

,

limit:

int

=

100

)

:

       

self

.

q

=

q

       

self

.

skip

=

skip

       

self

.

limit

=

limit

Use a class as a dependency

@

app.

get

(

"/items/"

)

async

def

read_items

(

commons: Annotated

[

CommonQueryParams

,

Depends

(

)

]

)

:

   

return

{

"q"

: commons.

q

,

"skip"

: commons.

skip

,

"limit"

: commons.

limit

}

When Depends() When no argument is passed, FastAPI automatically uses the parameter's type annotation (CommonQueryParams) as the dependency.


Sub-dependencies

Dependencies can have their own dependencies, forming a dependency chain:

Example

from

typing

import

Annotated

from

fastapi

import

Depends

,

FastAPI

app

=

FastAPI

(

)

Dependency function

def

query_extractor

(

q:

str

|

None

=

None

)

:

   

return

q

Sub-dependency: depends on query_extractor

def

query_checker

(

q:

str

=

Depends

(

query_extractor

)

)

:

   

if

q

==

"admin"

:

       

Sub-dependencies can perform validation

       

return

q +

" (checked)"

   

return

q

Route uses the sub-dependency

@

app.

get

(

"/items/"

)

async

def

read_items

(

q:

str

=

Depends

(

query_checker

)

)

:

   

return

{

"q"

: q

}

Execution flow:query_extractor -> query_checker -> route function


Using dependencies in decorators

Sometimes you only need a dependency's side effects (such as permission checks), not its return value. You can declare it in the decorator's dependencies parameter:

Example

from

fastapi

import

Depends

,

FastAPI

,

Header

,

HTTPException

app

=

FastAPI

(

)

Dependency: validate API Key

async

def

verify_api_key

(

x_api_key:

str

=

Header

(

)

)

:

   

if

x_api_key

!=

"secret-key"

:

       

raise

HTTPException

(

status_code

=

400

,

detail

=

"X-API-Key invalid"

)

Use a dependency in a decorator without needing its return value

@

app.

get

(

"/items/"

,

dependencies

=

[

Depends

(

verify_api_key

)

]

)

async

def

read_items

(

)

:

   

return

[

{

"item"

:

"Foo"

}

]

Using dependencies for an entire route group

@

app.

get

(

"/users/"

,

dependencies

=

[

Depends

(

verify_api_key

)

]

)

async

def

read_users

(

)

:

   

return

[

{

"user"

:

"Bar"

}

]


Global dependencies

can be done during FastAPI Declare global dependencies on the instance, applying to all routes:

Example

from

fastapi

import

Depends

,

FastAPI

,

Header

,

HTTPException

async

def

verify_token

(

x_token:

str

=

Header

(

)

)

:

   

if

x_token

!=

"fake-super-secret-token"

:

       

raise

HTTPException

(

status_code

=

400

,

detail

=

"X-Token header invalid"

)

Global dependency: all routes must pass token validation

app

=

FastAPI

(

dependencies

=

[

Depends

(

verify_token

)

]

)

@

app.

get

(

"/items/"

)

async

def

read_items

(

)

:

   

return

[

{

"item"

:

"Foo"

}

]

@

app.

get

(

"/users/"

)

async

def

read_users

(

)

:

   

return

[

{

"user"

:

"Bar"

}

]


Dependencies with yield

When a dependency needs to perform cleanup (such as closing a database connection), use yield:

Example

from

typing

import

Annotated

from

fastapi

import

Depends

,

FastAPI

app

=

FastAPI

(

)

Dependency with yield: create the connection before the request, close it after

def

get_db

(

)

:

    db

=

"database_connection"

 

Simulate creating a database connection

   

try

:

       

yield

db  

Provide the database connection during request processing

   

finally

:

       

print

(

"Close database connection"

)

 

Clean up resources after the request completes

@

app.

get

(

"/items/"

)

async

def

read_items

(

db:

str

=

Depends

(

get_db

)

)

:

   

return

{

"db"

: db

}

Execution flow:

  1. When a request arrives, execute the code yield before the yield, creating a database connection
  2. yield Pass the connection to the route function
  3. After the route function finishes, execute the cleanup code finally in the finally block

yield Dependencies are ideal for managing resources that need cleanup, such as database connections and file handles. The cleanup code runs regardless of whether the route function raises an exception.


Summary