Custom dependencies in FastAPI
User-defined dependencies are created to meet specific needs within your application. They involve the creation of custom functions or classes that offer specialized functionalities for your API routes. These personalized dependencies become especially useful when you aim to encapsulate intricate logic or when there is a desire to reuse code across multiple routes. In essence, they empower you to expand FastAPI’s capabilities to cater to your individual application requirements.
main.py
Product of Two Numbers
Let’s create a simple custom dependency to calculate the product of two numbers
- FastAPI Application Setup: The code begins by importing the
Depends
andFastAPI
classes from the FastAPI framework and creating an instance of theFastAPI
class, namedapp
. Thisapp
instance serves as the foundation for building a web application using FastAPI. It will handle incoming HTTP requests and route them to the appropriate functions for processing. - Dependency Injection for Calculating the Product: The code defines a Python function named
get_product
, which calculates the product of two numbersa
andb
. This function is used as a dependency for two different path operations. TheDepends(get_product)
syntax is used to declare a dependency on the result of theget_product
function. This means that before executing the path operations, the product of two numbers will be calculated by theget_product
function, and the result will be passed as theproduct
parameter to the path operations. - Path Operations for Handling Requests: The code defines two path operations,
my_path_operation
andread_item
, using the@app.get("/product")
decorator. These path operations respond to HTTP GET requests at the “/product” endpoint. Both path operations take aproduct
parameter, which is provided as a result of the dependency declared earlier. Themy_path_operation
path operation simply returns a dictionary containing the product, while theread_item
path operation does the same.
In this code product of the two numbers into the my_path_operation() function. Then my_path_operation() function will return the product of two numbers.
Python3
from fastapi import Depends, FastAPI app = FastAPI() def get_product(a: int , b: int ): """ Calculates the product of two numbers. Args: a: The first number. b: The second number. Returns: The product of a and b. """ return a * b # Declare a dependency on the product of two numbers async def my_path_operation(product: int = Depends(get_product)): """ A path operation that prints the product of two numbers. Args: product: The product of two numbers. """ return { "product" : product} # Use the decorator to add the path operation to the app @app .get( "/product" ) async def read_item(product: int = Depends(get_product)): return { "product" : product} |
then run the below command in terminal
uvicorn main:app --reload
You can now access the FastAPI endpoint at the following URL:
http://localhost:8000/product?a={value}&b={value}
http://localhost:8000/product?a=10&b=20
Output
Now, let’s explore another example to gain a better understanding of FastAPI dependencies.
Average of Two Number
- FastAPI Application Setup: The code begins by importing the
Depends
andFastAPI
classes from the FastAPI framework and creating an instance of theFastAPI
class, namedapp
. Thisapp
instance serves as the foundation for building a web application using FastAPI. It handles incoming HTTP requests and routes them to the appropriate functions for processing. - Custom Dependency for Calculating the Average: The code defines a Python function named
get_average
, which calculates the average of two numbersa
andb
. This function is used as a custom dependency for two different path operations. TheDepends(get_average)
syntax is used to declare a dependency on the result of theget_average
function. This means that before executing the path operations, the average of two numbers will be calculated by theget_average
function, and the result will be passed as theaverage
parameter to the path operations. - Path Operations for Handling Requests: The code defines a path operation named
my_path_operation
and uses the@app.get("/average")
decorator to set up an HTTP GET endpoint at the “/average” path. This path operation takes anaverage
parameter, which is provided as a result of the custom dependency declared earlier. Themy_path_operation
path operation simply returns a dictionary containing the calculated average.
Python3
from fastapi import Depends, FastAPI app = FastAPI() def get_average(a: int , b: int ): """ Calculates the average of two numbers. Args: a: The first number. b: The second number. Returns: The average of a and b. """ return (a + b) / 2 # Declare a dependency on the average of two numbers async def my_path_operation(average: float = Depends(get_average)): """ A path operation that prints the average of two numbers. Args: average: The average of two numbers. """ return { "average" : average} # Use the decorator to add the path operation to the app @app .get( "/average" ) async def get_average(average: float = Depends(get_average)): return { "average" : average} |
then run the below command in terminal
uvicorn main:app --reload
You can now access the FastAPI endpoint at the following URL:
http://localhost:8000/average?a={value}&b={value}
http://localhost:8000/average?a=10&b=20
Output
FastAPI – Dependencies
In this article, we will explore FastAPI – Dependencies. FastAPI is a state-of-the-art, high-performance web framework for creating Python-based APIs. It is built on the principles of dependency injection and type hinting, which facilitate the creation of clean, maintainable, and scalable code. This article delves deeper into topics such as Dependency Injection, Dependency Provider, Dependency Scope, and the use of dependencies in FastAPI, all with practical examples. Following this, we will examine the advantages of incorporating dependencies.
FastAPI’s dependency injection approach stands out as one of its pivotal features. Dependencies refer to the components that a class or function requires for its operation. When a function or class is invoked, FastAPI automatically supplies the dependencies as declared in the code.