What is the difference between Security and Depends in FastAPI?
Question:
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.
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.
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.
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.