0
0
FastAPIframework~30 mins

Shared dependencies in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Shared Dependencies in FastAPI
📖 Scenario: You are building a simple web API with FastAPI. You want to reuse a common dependency that provides a database connection object for multiple API endpoints.
🎯 Goal: Create a FastAPI app that uses a shared dependency function to provide a database connection string to two different endpoints.
📋 What You'll Learn
Create a dependency function called get_db that returns the string 'db_connection'.
Create a FastAPI app instance called app.
Create two GET endpoints: /items/ and /users/.
Both endpoints must use the get_db dependency to receive the database connection string.
Each endpoint should return a JSON response with a key db and the value from the dependency.
💡 Why This Matters
🌍 Real World
Shared dependencies in FastAPI help avoid repeating code for common resources like database connections, authentication, or configuration.
💼 Career
Understanding shared dependencies is essential for building scalable and maintainable APIs in professional FastAPI development.
Progress0 / 4 steps
1
Create the shared dependency function
Create a function called get_db that returns the string 'db_connection'.
FastAPI
Need a hint?

Define a simple function named get_db that returns the string 'db_connection'.

2
Create the FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

Use from fastapi import FastAPI and then create app = FastAPI().

3
Create the /items/ endpoint using the shared dependency
Create a GET endpoint /items/ using @app.get("/items/"). Add a parameter db that uses Depends(get_db). Return a dictionary with key db and value db.
FastAPI
Need a hint?

Use @app.get("/items/") and a function with parameter db: str = Depends(get_db). Return {"db": db}.

4
Create the /users/ endpoint using the shared dependency
Create a GET endpoint /users/ using @app.get("/users/"). Add a parameter db that uses Depends(get_db). Return a dictionary with key db and value db.
FastAPI
Need a hint?

Repeat the pattern from the previous step for the /users/ endpoint.