FastAPI Backend Development Bootcamp · Урок

Внедрение общих зависимостей

Реализуйте общие зависимости для сеансов базы данных, аутентификации пользователей или общей конфигурации конечных точек.

Урок 2 из 411 шагов

«Внедрение общих зависимостей» — бесплатный урок FastAPI Backend Development Bootcamp на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения FastAPI Backend Development Bootcamp, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс FastAPI Backend Development Bootcamp содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Intro to Common Dependencies

In FastAPI, dependencies are powerful. They help you share logic, manage resources, and keep your code clean.

Common dependencies are functions or classes that you reuse across many API endpoints. This prevents repetitive code and makes your application easier to maintain and test.

Think of them as reusable building blocks for your API.

Injecting Shared Configuration

Many applications need global settings, like API keys or database URLs. By injecting configuration, you can easily access these settings in any endpoint without resorting to global variables.

This keeps your configuration flexible and easy to update.

Demo: Simple Config Dependency

Let's create a dependency that returns a simple settings dictionary. In a real application, this might load from environment variables using Pydantic's BaseSettings.

from fastapi import FastAPI, Depends

app = FastAPI()

# This function acts as our dependency
def get_settings():
    return {"app_name": "CoddyKit API", "version": "1.0.0"}

@app.get("/info")
def read_info(settings: dict = Depends(get_settings)):
    return {"message": f"Welcome to {settings['app_name']} v{settings['version']}"}

# To run this:
# 1. Save as main.py
# 2. Run 'uvicorn main:app --reload'
# 3. Go to http://127.0.0.1:8000/info

Database Session Management

A common task for backend APIs is interacting with a database. Each request typically needs its own unique database "session" or connection.

Managing these sessions manually in every endpoint is tedious and error-prone. A dependency can handle creating and closing them automatically for you.

Demo: Database Session Dependency

Here's a simplified example of a get_db dependency. In a real application, this would connect to a database using an ORM like SQLAlchemy.

The yield keyword is key here!

from fastapi import FastAPI, Depends
from typing import Generator

app = FastAPI()

# This simulates a database session.
# In a real app, this would be a SQLAlchemy session.
class MockDBSession:
    def __init__(self):
        print("Opening DB session...")
    def close(self):
        print("Closing DB session...")
    def query(self, item_id: int):
        return {"id": item_id, "name": f"Item {item_id}"}

def get_db() -> Generator:
    db = MockDBSession()
    try:
        yield db  # This is where the endpoint gets the 'db' object
    finally:
        db.close() # This runs after the request is finished

@app.get("/items/{item_id}")
def read_item(item_id: int, db: MockDBSession = Depends(get_db)):
    # The 'db' object is provided by the dependency
    return db.query(item_id)

# To run this:
# 1. Save as main.py
# 2. Run 'uvicorn main:app --reload'
# 3. Go to http://127.0.0.1:8000/items/1

The Magic of `yield`

The yield keyword in our get_db function is very important.

  • Code before yield runs before the endpoint function. This is for setup (e.g., opening a database connection).
  • Code after yield runs after the endpoint function and its response. This is for teardown (e.g., closing the connection).

This pattern is called a "dependency with yield" or a "context manager dependency".

Injecting User Authentication

Most APIs need to know who is making a request. Authentication dependencies extract user information from request headers (like an API key or JWT token) and make it available to your endpoints.

This keeps your authentication logic separate and reusable across many routes.

Demo: Current User Dependency

Here's a basic dependency that simulates getting the current user. In a real application, this would involve validating a token from the request headers.

If the user isn't authenticated, it can raise an HTTPException to stop the request early.

from fastapi import FastAPI, Depends, HTTPException, status
from typing import Optional

app = FastAPI()

class User:
    def __init__(self, username: str, email: Optional[str] = None):
        self.username = username
        self.email = email

# This dependency simulates fetching the current user
def get_current_user(token: str = "some_valid_token") -> User:
    # In a real app, 'token' would come from request headers
    # and be validated against a database or auth service.
    if token != "some_valid_token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return User(username="jane_doe", email="jane@example.com")

@app.get("/me")
def read_current_user(current_user: User = Depends(get_current_user)):
    return {"username": current_user.username, "email": current_user.email}

# To run this:
# 1. Save as main.py
# 2. Run 'uvicorn main:app --reload'
# 3. Go to http://127.0.0.1:8000/me

Chaining & Reusing Dependencies

Dependencies can also depend on other dependencies! This allows for complex logic to be broken down into smaller, manageable pieces.

For example, a "current admin user" dependency might first depend on "current user", then check if that user has admin privileges.

This modularity is a core strength of FastAPI's dependency injection.

Check Your Understanding

Consider the following FastAPI dependency:

from fastapi import HTTPException, status

def check_api_key(api_key: str = "SECRET_KEY"):
    if api_key != "VALID_API_KEY":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid API Key"
        )
    return True

If an endpoint uses Depends(check_api_key) and a request comes in without the correct API_KEY, what will happen?

Common Dependencies: Key Takeaways

We've explored how to inject common dependencies in FastAPI:

  • Configuration: Share application settings easily across endpoints.
  • Database Sessions: Manage database connections per request using yield for proper setup and teardown.
  • User Authentication: Centralize logic for identifying and validating users.

Dependencies promote clean, reusable, and testable code by keeping cross-cutting concerns separate from your main endpoint logic.

Можно начать бесплатно

Изучай FastAPI Backend Development Bootcamp с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
21
Уроки
84

Часто задаваемые вопросы

Урок «Внедрение общих зависимостей» бесплатный?

Да — полный текст урока «Внедрение общих зависимостей» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс FastAPI Backend Development Bootcamp, подпишись на CoddyKit PRO. Курс FastAPI Backend Development Bootcamp содержит 4 уроков всего.

Чему я научусь в уроке «Внедрение общих зависимостей»?

Реализуйте общие зависимости для сеансов базы данных, аутентификации пользователей или общей конфигурации конечных точек. Ты практикуешь FastAPI Backend Development Bootcamp с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать FastAPI Backend Development Bootcamp?

Предыдущий опыт не требуется. FastAPI Backend Development Bootcamp на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Внедрение общих зависимостей»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке FastAPI Backend Development Bootcamp?

Да. Каждый урок FastAPI Backend Development Bootcamp включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Зависимости в FastAPI
  2. Внедрение общих зависимостей
  3. Зависимости на основе классов и yield
  4. Глобальные зависимости и вложенные зависимости
← Назад к FastAPI Backend Development Bootcamp