0Pricing
FastAPI Backend Development Bootcamp · 강의

FastAPI와 PostgreSQL 연결

SQLAlchemy를 사용하여 FastAPI 애플리케이션과 PostgreSQL 데이터베이스 간의 연결을 설정합니다.

FastAPI와 PostgreSQL 연결은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Connect to a Database?

Web applications often need to store and retrieve data persistently. This data could be user profiles, product listings, or transaction records.

Instead of losing data when your app restarts, we connect to a database. Databases provide a structured and efficient way to manage large amounts of information.

Introducing PostgreSQL

PostgreSQL is a powerful, open-source relational database system. It's known for its robustness, feature set, and performance.

  • Reliable: Ensures data integrity.
  • Scalable: Handles large data volumes and high user loads.
  • Extensible: Supports custom data types and functions.

Many FastAPI applications use PostgreSQL as their primary data store.

The Database Connection URL

To connect to any database, you need a connection string or URL. This URL tells SQLAlchemy (our ORM) how to find and authenticate with your database.

For PostgreSQL, a typical URL looks like this:

postgresql://user:password@host:port/database_name

It's best practice to store this URL in an environment variable for security and flexibility.

Creating the SQLAlchemy Engine

The first step in SQLAlchemy is to create an Engine. The Engine is responsible for communicating with the database.

We use create_engine from sqlalchemy to establish this connection. For our runnable example, we'll use SQLite, but the principle for PostgreSQL is the same – just the URL changes.

from sqlalchemy import create_engine

# For PostgreSQL, this would be:
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/dbname"
# For a runnable example, we'll use SQLite:
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)

print("Engine created successfully!")

Managing Database Sessions

Directly interacting with the database through the engine isn't ideal for every request. Instead, we use Sessions.

A Session is like a temporary workspace for your database operations. It handles transactions and ensures changes are committed or rolled back properly.

We create a SessionLocal class using sessionmaker, which will produce session instances.

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

# Using SQLite for a runnable example
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

print("SessionLocal configured!")

The Declarative Base (Review)

Recall from the previous lesson that declarative base is used to define your SQLAlchemy models. All your ORM models will inherit from this base.

Even though we won't define a new model here, it's an essential part of the setup for any ORM interaction.

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

print("Declarative Base initialized.")

FastAPI Dependency: get_db()

FastAPI's powerful Dependency Injection system is perfect for managing database sessions.

We'll create a function, get_db, that creates a new database session for each request, uses it, and then closes it automatically. The yield keyword is key here!

from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Assuming these are defined elsewhere or imported
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

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

print("get_db dependency function defined.")

Using the Session in an Endpoint

Now, you can inject the database session directly into your FastAPI endpoint functions using Depends.

FastAPI will call get_db(), pass the session to your route, and ensure it's closed after the request is handled.

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session

# For this snippet, we'll use a mock get_db to make it runnable
class MockSession:
    def close(self): pass

def get_db_mock():
    yield MockSession()

app = FastAPI()

@app.get("/db-status")
def read_db_status(db: Session = Depends(get_db_mock)):
    # In a real app, 'db' would be your actual SQLAlchemy session
    return {"message": "Database session received!"}

print("FastAPI endpoint defined using DB dependency.")

Full FastAPI-PostgreSQL Setup

Here's a complete example bringing everything together. This app sets up the connection to a database (using SQLite for local testing, but easily swappable for PostgreSQL) and exposes an endpoint that uses a database session.

To run this with a real PostgreSQL, replace the SQLALCHEMY_DATABASE_URL and ensure your PostgreSQL server is running.

from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
import uvicorn

# --- Database Configuration (for PostgreSQL, replace URL) ---
# For a runnable example, we'll use SQLite in-memory:
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# For PostgreSQL, it would be:
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/dbname"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# --- Dependency to get DB session ---
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# --- FastAPI Application ---
app = FastAPI()

@app.get("/connect-test")
def connect_test(db: Session = Depends(get_db)):
    # We've successfully received a DB session 'db'
    # In a real app, you'd perform DB operations here.
    return {"status": "Connected to DB", "db_type": SQLALCHEMY_DATABASE_URL.split('://')[0]}

# To run this, save as 'main.py' and run 'uvicorn main:app --reload'
# if __name__ == "__main__":
#    uvicorn.run(app, host="0.0.0.0", port=8000)

Quick Check: DB Session

Consider the get_db dependency function:

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

What is the primary reason for using yield db instead of return db in this FastAPI dependency?

Recap: Connecting FastAPI to PostgreSQL

In this lesson, you learned the essential steps to connect your FastAPI application to a database, specifically focusing on PostgreSQL (with runnable SQLite examples for convenience).

  • We defined the Database URL to locate the database.
  • We used create_engine to establish the connection.
  • We set up SessionLocal for managing database sessions.
  • We created a get_db dependency using yield to inject and manage sessions per request in FastAPI.

Now your FastAPI app is ready to interact with a database! Next, we'll learn how to perform CRUD operations.

자주 묻는 질문

“FastAPI와 PostgreSQL 연결” 강의는 무료인가요?

네 — “FastAPI와 PostgreSQL 연결” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“FastAPI와 PostgreSQL 연결”에서 뭘 배우나요?

SQLAlchemy를 사용하여 FastAPI 애플리케이션과 PostgreSQL 데이터베이스 간의 연결을 설정합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“FastAPI와 PostgreSQL 연결” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. SQLAlchemy ORM 기초
  2. FastAPI와 PostgreSQL 연결
  3. SQLAlchemy를 활용한 CRUD 작업
  4. Alembic을 활용한 데이터베이스 마이그레이션
← FastAPI Backend Development Bootcamp(으)로 돌아가기