Categories
Tags
30days AI ai backend blog blogging booking burnout career chatbot cms coding design development devops django docker email express fastapi flight Flight Booking System full stack full-stack gmail GPT-3 interviews journey LinkedIn MERN mongodb NextJS nextjs notion OpenAI openai planning portfolio programming project python react ReactJS search sendgrid smtp software software development tailwind
288 words
1 minutes
Day 9 of 30 Days of FastAPI - Dependency Injection — Sharing Logic Gracefully
In a small app, you might just use a global variable for your database. But in a real app, that leads to “spaghetti code.” Today, I learned how to use FastAPI’s Depends to manage shared resources.
1. What is a Dependency?
A dependency is just a function. FastAPI will run this function before your endpoint runs and pass the result into your route.
2. Implementation: Injecting the Mock DB
Instead of accessing db globally, we can create a dependency that “provides” the database to our routes.
from fastapi import FastAPI, Depends
from typing import Annotated
app = FastAPI()
# 1. Define the dependency
def get_db():
# In a real app, this is where you'd open a DB session
return db
# 2. Use it in a route
@app.get("/items/")
async def read_items(database: Annotated[list, Depends(get_db)]):
return {"data": database}

3. Why use Annotated?
You’ll notice I used Annotated. This is the modern, recommended way to write FastAPI dependencies. It makes the code more readable and plays nicely with other Python tools (like linters and static analyzers).
4. Benefits I Discovered Today:
- Dry (Don’t Repeat Yourself): If I want to add logging to every database call, I only have to change it in the
get_dbfunction. - Security: You can use dependencies to check if a user is logged in before the route even begins.
- Validation: Dependencies can have their own
QueryandPathparameters, meaning they can validate data before it ever reaches your main logic.
🛠️ Implementation Checklist
- Created a
get_dbdependency function. - Refactored the
POSTandGETroutes to useDepends(get_db). - Verified that the API still functions exactly as before (but with cleaner code!).
- Explored how dependencies show up in Swagger UI (they look like regular parameters).
📚 Resources
- Official Docs: FastAPI Dependencies - First Steps
- Book: FastAPI: Modern Python Web Development (Chapter 5: Dependency Injection).
Day 9 of 30 Days of FastAPI - Dependency Injection — Sharing Logic Gracefully
https://beyond400.vercel.app/posts/fastapi-09/

