0Pricing
Python Academy · Lesson

Dependency Injection and Authentication

Use FastAPI's DI system for shared logic and JWT-based auth.

Dependency Injection and Authentication is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Dependency Injection?

FastAPI's Depends() lets you declare shared logic (DB sessions, auth checks, config) that is automatically injected into route handlers.

from fastapi import FastAPI, Depends
app = FastAPI()

def get_db():
    db = connect_db()
    try: yield db
    finally: db.close()

@app.get("/users")
def list_users(db = Depends(get_db)):
    return db.query_all("users")

Dependency Functions

A dependency is any callable. It can be a function, class, or another dependency-using function.

from fastapi import Depends, FastAPI
app = FastAPI()

def common_params(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

@app.get("/items")
def list_items(params: dict = Depends(common_params)):
    return params

@app.get("/users")
def list_users(params: dict = Depends(common_params)):
    return params

Class Dependencies

Use a class as a dependency to group related settings. The class is called with its __init__ arguments injected.

from fastapi import Depends, FastAPI, Query
app = FastAPI()

class Pagination:
    def __init__(self, page: int = Query(1,ge=1), size: int = Query(10,ge=1,le=100)):
        self.page = page
        self.size = size
        self.offset = (page - 1) * size

@app.get("/items")
def list_items(pag: Pagination = Depends()):
    return {"offset": pag.offset, "size": pag.size}

OAuth2 Password Bearer

Use OAuth2PasswordBearer to read a Bearer token from the Authorization header.

from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()

oauth2 = OAuth2PasswordBearer(tokenUrl="/token")

@app.get("/me")
def me(token: str = Depends(oauth2)):
    return {"token": token}   # validate token here

JWT Tokens

Create and verify JWT tokens with python-jose (or pyjwt). Return a token on login; verify it in every protected route.

# pip install python-jose passlib
from jose import jwt, JWTError

SECRET_KEY = "change-me"
ALGORITHM = "HS256"

def create_token(data: dict) -> str:
    return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)

def verify_token(token: str) -> dict:
    return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])

Current User Dependency

Build a get_current_user dependency that verifies the JWT and returns the authenticated user.

from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError

oauth2 = OAuth2PasswordBearer(tokenUrl="/token")

def get_current_user(token: str = Depends(oauth2)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        return payload["sub"]
    except JWTError:
        raise HTTPException(status_code=401, detail="Invalid token")

# @app.get("/me")
# def me(user=Depends(get_current_user)): return user

Password Hashing

Never store plain passwords. Use passlib to hash with bcrypt.

from passlib.context import CryptContext

pwd_ctx = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_pw(plain: str) -> str:
    return pwd_ctx.hash(plain)

def verify_pw(plain: str, hashed: str) -> bool:
    return pwd_ctx.verify(plain, hashed)

Token Endpoint

Implement POST /token that accepts form credentials, verifies password, and returns a JWT.

from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()

@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
    user = get_user_by_username(form.username)
    if not user or not verify_pw(form.password, user.hashed_pw):
        raise HTTPException(status_code=401, detail="Bad credentials")
    token = create_token({"sub": form.username})
    return {"access_token": token, "token_type": "bearer"}

API Key Authentication

For simpler cases, validate an API key from a header or query parameter.

from fastapi import Depends, HTTPException, Security
from fastapi.security import APIKeyHeader

API_KEY_HEADER = APIKeyHeader(name="X-API-Key")

def require_api_key(key: str = Security(API_KEY_HEADER)):
    if key != "secret-key":
        raise HTTPException(status_code=403, detail="Forbidden")
    return key

Role-Based Access Control

Layer permissions on top of auth by adding role checks to dependencies.

from fastapi import Depends, HTTPException

def require_admin(user=Depends(get_current_user)):
    if user.get("role") != "admin":
        raise HTTPException(status_code=403, detail="Admins only")
    return user

# @app.delete("/users/{uid}")
# def delete_user(uid: int, admin=Depends(require_admin)):

Dependency Caching

By default, a dependency is called once per request and its result is shared among all routes that use it in that request.

# The same db session object is shared:
@app.get("/summary")
def summary(
    db = Depends(get_db),      # db resolved once
    stats = Depends(get_stats) # get_stats also uses get_db — same db instance
): ...

Quick Check

What does Depends() do in FastAPI?

Recap

Use Depends(func) to inject shared logic. Build auth with OAuth2PasswordBearer, JWT tokens, and a get_current_user dependency. Hash passwords with passlib/bcrypt. Add role checks as further dependencies.

Frequently asked questions

Is the “Dependency Injection and Authentication” lesson free?

Yes — the full text of “Dependency Injection and Authentication” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Dependency Injection and Authentication”?

Use FastAPI's DI system for shared logic and JWT-based auth. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Dependency Injection and Authentication” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. FastAPI Project Setup and First Endpoint
  2. Path Parameters, Query Params, and Request Bodies
  3. Dependency Injection and Authentication
  4. Async Endpoints and Database Integration
← Back to Python Academy