Dependencies - Depends() and Security()

Depends()

Dependencies are handled mainly with the special function Depends() that takes a callable.

Here is the reference for it and its parameters.

You can import it directly from fastapi:

  1. from fastapi import Depends

fastapi.Depends

  1. Depends(dependency=None, *, use_cache=True)

Declare a FastAPI dependency.

It takes a single “dependable” callable (like a function).

Don’t call it directly, FastAPI will call it for you.

Read more about it in the FastAPI docs for Dependencies.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. app = FastAPI()
  4. async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
  5. return {"q": q, "skip": skip, "limit": limit}
  6. @app.get("/items/")
  7. async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
  8. return commons
PARAMETERDESCRIPTION
dependency

A “dependable” callable (like a function).

Don’t call it directly, FastAPI will call it for you, just pass the object directly.

TYPE: Optional[Callable[…, Any]] DEFAULT: None

use_cache

By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request.

Set use_cache to False to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request.

TYPE: bool DEFAULT: True

Source code in fastapi/param_functions.py

  1. 2220
  2. 2221
  3. 2222
  4. 2223
  5. 2224
  6. 2225
  7. 2226
  8. 2227
  9. 2228
  10. 2229
  11. 2230
  12. 2231
  13. 2232
  14. 2233
  15. 2234
  16. 2235
  17. 2236
  18. 2237
  19. 2238
  20. 2239
  21. 2240
  22. 2241
  23. 2242
  24. 2243
  25. 2244
  26. 2245
  27. 2246
  28. 2247
  29. 2248
  30. 2249
  31. 2250
  32. 2251
  33. 2252
  34. 2253
  35. 2254
  36. 2255
  37. 2256
  38. 2257
  39. 2258
  40. 2259
  41. 2260
  42. 2261
  43. 2262
  44. 2263
  45. 2264
  46. 2265
  47. 2266
  48. 2267
  49. 2268
  50. 2269
  51. 2270
  52. 2271
  53. 2272
  54. 2273
  55. 2274
  56. 2275
  57. 2276
  58. 2277
  1. def Depends( # noqa: N802
  2. dependency: Annotated[
  3. Optional[Callable[, Any]],
  4. Doc(
  5. “””
  6. A dependable callable (like a function).
  7. Dont call it directly, FastAPI will call it for you, just pass the object
  8. directly.
  9. “””
  10. ),
  11. ] = None,
  12. ,
  13. use_cache: Annotated[
  14. bool,
  15. Doc(
  16. “””
  17. By default, after a dependency is called the first time in a request, if
  18. the dependency is declared again for the rest of the request (for example
  19. if the dependency is needed by several dependencies), the value will be
  20. re-used for the rest of the request.
  21. Set use_cache to False to disable this behavior and ensure the
  22. dependency is called again (if declared more than once) in the same request.
  23. “””
  24. ),
  25. ] = True,
  26. ) -> Any:
  27. “””
  28. Declare a FastAPI dependency.
  29. It takes a single dependable callable (like a function).
  30. Dont call it directly, FastAPI will call it for you.
  31. Read more about it in the
  32. FastAPI docs for Dependencies.
  33. *Example
  34. python</span>
  35. <span> from typing import Annotated</span>
  36. <span> from fastapi import Depends, FastAPI</span>
  37. <span> app = FastAPI()</span>
  38. <span> async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):</span>
  39. <span> return {"q": q, "skip": skip, "limit": limit}</span>
  40. <span> @app.get("/items/")</span>
  41. <span> async def read_items(commons: Annotated[dict, Depends(common_parameters)]):</span>
  42. <span> return commons</span>
  43. <span>
  44. “””
  45. return params.Depends(dependency=dependency, use_cache=use_cache)

Security()

For many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, using Depends().

But when you want to also declare OAuth2 scopes, you can use Security() instead of Depends().

You can import Security() directly from fastapi:

  1. from fastapi import Security

fastapi.Security

  1. Security(dependency=None, *, scopes=None, use_cache=True)

Declare a FastAPI Security dependency.

The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI and the automatic UI docs (by default at /docs).

It takes a single “dependable” callable (like a function).

Don’t call it directly, FastAPI will call it for you.

Read more about it in the FastAPI docs for Security and in the FastAPI docs for OAuth2 scopes.

Example

  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI
  3. from .db import User
  4. from .security import get_current_active_user
  5. app = FastAPI()
  6. @app.get("/users/me/items/")
  7. async def read_own_items(
  8. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  9. ):
  10. return [{"item_id": "Foo", "owner": current_user.username}]
PARAMETERDESCRIPTION
dependency

A “dependable” callable (like a function).

Don’t call it directly, FastAPI will call it for you, just pass the object directly.

TYPE: Optional[Callable[…, Any]] DEFAULT: None

scopes

OAuth2 scopes required for the path operation that uses this Security dependency.

The term “scope” comes from the OAuth2 specification, it seems to be intentionaly vague and interpretable. It normally refers to permissions, in cases to roles.

These scopes are integrated with OpenAPI (and the API docs at /docs). So they are visible in the OpenAPI specification. )

TYPE: Optional[Sequence[str]] DEFAULT: None

use_cache

By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request.

Set use_cache to False to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request.

TYPE: bool DEFAULT: True

Source code in fastapi/param_functions.py

  1. 2280
  2. 2281
  3. 2282
  4. 2283
  5. 2284
  6. 2285
  7. 2286
  8. 2287
  9. 2288
  10. 2289
  11. 2290
  12. 2291
  13. 2292
  14. 2293
  15. 2294
  16. 2295
  17. 2296
  18. 2297
  19. 2298
  20. 2299
  21. 2300
  22. 2301
  23. 2302
  24. 2303
  25. 2304
  26. 2305
  27. 2306
  28. 2307
  29. 2308
  30. 2309
  31. 2310
  32. 2311
  33. 2312
  34. 2313
  35. 2314
  36. 2315
  37. 2316
  38. 2317
  39. 2318
  40. 2319
  41. 2320
  42. 2321
  43. 2322
  44. 2323
  45. 2324
  46. 2325
  47. 2326
  48. 2327
  49. 2328
  50. 2329
  51. 2330
  52. 2331
  53. 2332
  54. 2333
  55. 2334
  56. 2335
  57. 2336
  58. 2337
  59. 2338
  60. 2339
  61. 2340
  62. 2341
  63. 2342
  64. 2343
  65. 2344
  66. 2345
  67. 2346
  68. 2347
  69. 2348
  70. 2349
  71. 2350
  72. 2351
  73. 2352
  74. 2353
  75. 2354
  76. 2355
  77. 2356
  78. 2357
  79. 2358
  80. 2359
  81. 2360
  1. def Security( # noqa: N802
  2. dependency: Annotated[
  3. Optional[Callable[, Any]],
  4. Doc(
  5. “””
  6. A dependable callable (like a function).
  7. Dont call it directly, FastAPI will call it for you, just pass the object
  8. directly.
  9. “””
  10. ),
  11. ] = None,
  12. ,
  13. scopes: Annotated[
  14. Optional[Sequence[str]],
  15. Doc(
  16. “””
  17. OAuth2 scopes required for the path operation that uses this Security
  18. dependency.
  19. The term scope comes from the OAuth2 specification, it seems to be
  20. intentionaly vague and interpretable. It normally refers to permissions,
  21. in cases to roles.
  22. These scopes are integrated with OpenAPI (and the API docs at /docs).
  23. So they are visible in the OpenAPI specification.
  24. )
  25. “””
  26. ),
  27. ] = None,
  28. use_cache: Annotated[
  29. bool,
  30. Doc(
  31. “””
  32. By default, after a dependency is called the first time in a request, if
  33. the dependency is declared again for the rest of the request (for example
  34. if the dependency is needed by several dependencies), the value will be
  35. re-used for the rest of the request.
  36. Set use_cache to False to disable this behavior and ensure the
  37. dependency is called again (if declared more than once) in the same request.
  38. “””
  39. ),
  40. ] = True,
  41. ) -> Any:
  42. “””
  43. Declare a FastAPI Security dependency.
  44. The only difference with a regular dependency is that it can declare OAuth2
  45. scopes that will be integrated with OpenAPI and the automatic UI docs (by default
  46. at /docs).
  47. It takes a single dependable callable (like a function).
  48. Dont call it directly, FastAPI will call it for you.
  49. Read more about it in the
  50. FastAPI docs for Security and
  51. in the
  52. FastAPI docs for OAuth2 scopes.
  53. *Example
  54. python</span>
  55. <span> from typing import Annotated</span>
  56. <span> from fastapi import Depends, FastAPI</span>
  57. <span> from .db import User</span>
  58. <span> from .security import get_current_active_user</span>
  59. <span> app = FastAPI()</span>
  60. <span> @app.get("/users/me/items/")</span>
  61. <span> async def read_own_items(</span>
  62. <span> current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]</span>
  63. <span> ):</span>
  64. <span> return [{"item_id": "Foo", "owner": current_user.username}]</span>
  65. <span>
  66. “””
  67. return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)