FastAPI Training: Core Concepts
1. Dependency Injection
Dependency Injection is a design pattern used in FastAPI to manage and inject dependencies into your endpoints. This pattern helps in decoupling the components of your application, making it easier to test and maintain.
Imagine you are building a library management system where each book needs to be checked for availability before being issued. Instead of writing the availability check logic directly within each endpoint, you can create a dependency that handles this check. This way, the logic is centralized and can be reused across multiple endpoints.
Here is an example of how to use dependency injection in FastAPI:
from fastapi import Depends, FastAPI app = FastAPI() class BookChecker: def is_available(self, book_id: int): # Logic to check book availability return True def get_book_checker(): return BookChecker() @app.get("/issue_book/{book_id}") def issue_book(book_id: int, book_checker: BookChecker = Depends(get_book_checker)): if book_checker.is_available(book_id): return {"message": "Book is available and issued"} return {"message": "Book is not available"}
In this example, the get_book_checker function returns an instance of BookChecker, which is then injected into the issue_book endpoint using the Depends function. This ensures that the availability check logic is reusable and centralized.
2. Path Parameters and Query Parameters
Path Parameters and Query Parameters are essential components in defining the structure and behavior of your API endpoints. Path parameters are used to capture values from the URL path, while query parameters are used to capture values from the query string.
Consider a scenario where you are building a weather API. The path parameter could be used to specify the city for which the weather information is requested, while the query parameter could be used to specify additional details like the date range.
Here is an example of how to use path and query parameters in FastAPI:
from fastapi import FastAPI app = FastAPI() @app.get("/weather/{city}") def get_weather(city: str, start_date: str = None, end_date: str = None): weather_data = { "city": city, "start_date": start_date, "end_date": end_date, "temperature": "25°C", "conditions": "Sunny" } return weather_data
In this example, the city is a path parameter that captures the city name from the URL. The start_date and end_date are query parameters that capture additional information from the query string. This allows users to request weather data for a specific city and optionally specify a date range.