0
0
FastAPIframework~30 mins

Class-based dependencies in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Class-based dependencies in FastAPI
📖 Scenario: You are building a simple FastAPI app that uses a class to manage a counter. This counter will be shared as a dependency in your API endpoints.
🎯 Goal: Create a FastAPI app with a class-based dependency that tracks a counter value. Use this dependency in an endpoint to return the current count.
📋 What You'll Learn
Create a class called Counter with an attribute count initialized to 0
Add a method increment in Counter that increases count by 1
Create a FastAPI app instance called app
Use Depends to inject the Counter class as a dependency in an endpoint
Create a GET endpoint /count that calls increment and returns the current count
💡 Why This Matters
🌍 Real World
Class-based dependencies help organize and reuse logic that needs to maintain state or configuration in web APIs.
💼 Career
Understanding class-based dependencies is important for building scalable and maintainable FastAPI applications in professional backend development.
Progress0 / 4 steps
1
Create the Counter class
Create a class called Counter with an attribute count set to 0 inside the __init__ method.
FastAPI
Need a hint?

Define a class with class Counter:. Inside, create def __init__(self): and set self.count = 0.

2
Add increment method to Counter
Add a method called increment inside the Counter class that increases self.count by 1.
FastAPI
Need a hint?

Define def increment(self): and inside it add self.count += 1.

3
Create FastAPI app and dependency
Import FastAPI and Depends from fastapi. Create an app instance called app. Define a function get_counter that returns a new Counter instance.
FastAPI
Need a hint?

Import FastAPI and Depends. Create app = FastAPI(). Define get_counter() that returns Counter().

4
Create endpoint using class-based dependency
Create a GET endpoint /count using @app.get("/count"). Add a parameter counter with type Counter and default value Depends(get_counter). Inside the function, call counter.increment() and return a dictionary with key count and value counter.count.
FastAPI
Need a hint?

Use @app.get("/count") to create the endpoint. Add counter: Counter = Depends(get_counter) as parameter. Call counter.increment() and return {"count": counter.count}.