Skip to main content

What are dependencies

Understanding Dependencies in FastAPI

Dependencies in FastAPI are a way of declaring additional functionality that your path operation needs to operate. These can be external services, database connections, or other operational functions. FastAPI uses a modern and easy-to-use system for dependencies inspired by Python's decorators and the dependency injection systems used in frameworks like Angular.

What are Dependencies?

In simple terms, a dependency is a piece of code that your application needs to function correctly. A dependency can be a module, package, or function in your application. It's called a 'dependency' because your application depends on it, and it cannot run correctly without it.

How FastAPI Handles Dependencies

FastAPI provides a built-in dependency system that allows you to declare your dependencies at different levels of your application. This means you can have dependencies for your entire application (global dependencies), for specific path operations, or even for specific parameters.

To create a dependency in FastAPI, you use the Depends class. Here's an example of how to declare a dependency:

from fastapi import Depends, FastAPI

def get_db():
db = "Connecting to the database"
try:
yield db
finally:
db = "Disconnecting from the database"

app = FastAPI()

@app.get("/items/")
def read_items(db = Depends(get_db)):
return {"db_status": db}

In this example, get_db is a dependency. Whenever a path operation uses Depends(get_db), FastAPI will call get_db and use its return value to satisfy the dependency.

Dependency Injection

The process of providing the dependencies that an object needs is called dependency injection. FastAPI uses dependency injection to provide your path operations with their dependencies. This is done automatically by FastAPI, so you don't have to worry about manually providing your dependencies to your path operations.

Benefits of Using Dependencies

  • Reuse: Dependencies allow you to reuse code. You can define a dependency once, and use it across multiple path operations.

  • Organization: Dependencies can help you keep your code organized. By grouping related functionality into dependencies, you can keep your path operations clean and easy to read.

  • Testing: Dependencies make your code easier to test. You can replace your dependencies with mock objects in your tests, allowing you to test your path operations in isolation.

FastAPI's dependency system is a powerful tool that can help you write clean, well-organized, and reusable code. It's one of the many features that make FastAPI a great choice for writing modern, scalable Python web applications.