Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Security and Depends in FastAPI?

Tags:

python

fastapi

This is my code:

from fastapi import FastAPI, Depends, Security
from fastapi.security import HTTPBearer

bearer = HTTPBearer()

@app.get("/")
async def root(q = Security(bearer)):
    return {'q': q}

@app.get("/Depends")
async def root(q = Depends(bearer)):
    return {'q': q,}

Both routes give precisely the same result and act in the same manner. I checked the source code and found that the Security class inherits from the Depedends class. But I have no understanding in what way. Can you please show me the differences and why would I prefer to use Security over Depends.

like image 694
Testing man Avatar asked Sep 12 '25 08:09

Testing man


1 Answers

TL;DR

Use Security for security related dependencies as it is thought as a convenience for the devs. Use Depends when more general dependencies are needed.

Nevertheless, you may use these two interchangeably (for security related requirements).

Original answer

The Security class is a more specialized version of Depends.

In the source code

https://github.com/tiangolo/fastapi/blob/master/fastapi/param_functions.py

other types of dependencies are defined, such as Form, Body and File. As their names suggest, they are specialized for a particular task/data.

Basically there is no big difference between the two. The Security is more specialized than Depends, so the output is the same. It is more of a convenience for the developer.

like image 125
lsabi Avatar answered Sep 14 '25 22:09

lsabi