공통 의존성 주입
엔드포인트 전반에서 데이터베이스 세션, 사용자 인증 또는 공유 설정에 사용할 공통 의존성을 구현합니다.
공통 의존성 주입은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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/infoDatabase 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/1The Magic of `yield`
The yield keyword in our get_db function is very important.
- Code before
yieldruns before the endpoint function. This is for setup (e.g., opening a database connection). - Code after
yieldruns 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/meChaining & 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
yieldfor 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.
자주 묻는 질문
“공통 의존성 주입” 강의는 무료인가요?
네 — “공통 의존성 주입” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“공통 의존성 주입”에서 뭘 배우나요?
엔드포인트 전반에서 데이터베이스 세션, 사용자 인증 또는 공유 설정에 사용할 공통 의존성을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“공통 의존성 주입” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.