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

  1. FastAPI Application Setup: The code begins by importing the Depends and FastAPI classes from the FastAPI framework and creating an instance of the FastAPI class, named app. This app 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.
  2. Dependency Injection for Calculating the Product: The code defines a Python function named get_product, which calculates the product of two numbers a and b. This function is used as a dependency for two different path operations. The Depends(get_product) syntax is used to declare a dependency on the result of the get_product function. This means that before executing the path operations, the product of two numbers will be calculated by the get_product function, and the result will be passed as the product parameter to the path operations.
  3. Path Operations for Handling Requests: The code defines two path operations, my_path_operation and read_item, using the @app.get("/product") decorator. These path operations respond to HTTP GET requests at the “/product” endpoint. Both path operations take a product parameter, which is provided as a result of the dependency declared earlier. The my_path_operation path operation simply returns a dictionary containing the product, while the read_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

Output :

Now, let’s explore another example to gain a better understanding of FastAPI dependencies.

Average of Two Number

  1. FastAPI Application Setup: The code begins by importing the Depends and FastAPI classes from the FastAPI framework and creating an instance of the FastAPI class, named app. This app 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.
  2. Custom Dependency for Calculating the Average: The code defines a Python function named get_average, which calculates the average of two numbers a and b. This function is used as a custom dependency for two different path operations. The Depends(get_average) syntax is used to declare a dependency on the result of the get_average function. This means that before executing the path operations, the average of two numbers will be calculated by the get_average function, and the result will be passed as the average parameter to the path operations.
  3. 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 an average parameter, which is provided as a result of the custom dependency declared earlier. The my_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

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.

Similar Reads

Dependency Injection

Dependency Injection: Dependency Injection is a design pattern that allows code to be isolated from its dependencies. This means that code doesn’t need to know how to create or manage its dependencies; it just needs to know how to use them. DI is achieved by injecting dependencies into the code at runtime. While this can be done manually, using a DI framework like FastAPI greatly simplifies the process....

Built-in dependencies in FastAPI

FastAPI provides a set of built-in dependencies that are readily available for use. These built-in dependencies cover common scenarios such as handling HTTP requests, security, and data validation. They simplify the process of incorporating essential functionality into your API routes. Examples of built-in dependencies include Request, Query, and Path, which allow you to extract information from incoming HTTP requests....

Custom dependencies in FastAPI

...

Contact Us