Dependency injection is a design pattern in which an object receives other objects that it depends on. In FastAPI, dependency injection is used to provide shared functionality across multiple endpoints. Dependencies can be used for tasks such as authentication, database connections, and logging.
Here is a simple example of using dependency injection in FastAPI:
from fastapi import Depends, FastAPI
app = FastAPI()
# Define a dependency function
def get_db():
# Here you can establish a database connection
db = "Mock Database Connection"
try:
yield db
finally:
# Close the database connection
pass
# Use the dependency in an endpoint
@app.get("/items/")
async def read_items(db = Depends(get_db)):
return {"db": db}
Middleware is a function that works with every request before it is processed by any specific path operation, and also with every response before returning it. It can be used for tasks such as logging, authentication, and CORS handling.
Here is an example of adding middleware to a FastAPI application:
from fastapi import FastAPI, Request
import time
app = FastAPI()
# Define middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
@app.get("/")
async def read_root():
return {"Hello": "World"}
Background tasks in FastAPI allow you to run functions after returning a response. This is useful for tasks such as sending emails, generating reports, or performing data cleaning operations.
Here is an example of using background tasks in FastAPI:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="Some notification")
return {"message": "Notification sent in the background"}
FastAPI allows you to define custom request and response models using Pydantic. This provides automatic data validation, serialization, and documentation generation.
Here is an example of using custom request and response models:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Define request model
class Item(BaseModel):
name: str
price: float
# Define response model
class ItemResponse(BaseModel):
name: str
price: float
discount: float
@app.post("/items/", response_model=ItemResponse)
async def create_item(item: Item):
discounted_price = item.price * 0.9
return {"name": item.name, "price": item.price, "discount": discounted_price}
Testing is an essential part of the development process. FastAPI provides built - in support for testing using the TestClient
from the fastapi.testclient
module.
Here is an example of testing a FastAPI application:
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
FastAPI’s advanced features provide a powerful set of tools for building high - performance, robust, and maintainable APIs. By understanding and using features such as dependency injection, middleware, background tasks, custom request and response models, and testing, developers can take full advantage of FastAPI’s capabilities. These features not only enhance the functionality of the application but also improve the overall development experience.