데이터 사이언스 팀플 관련하여 백엔드를 FastAPI로 구현하게 되어 기본적인 CRUD과정부터 마지막 구현까지 블로그를 통하여 정리하려고 한다.
기본적으로 CRUD를 구현하기 위한 구조는 다음과 같다.
각 역할을 정리하면
이때의 데이터 흐름 구조는 다음과 같다.
데이터의 전체적인 흐름은 위와 같다.
이제 코드를 살펴보며 확인해보자
환자 생성 코드 설명
# patients.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from database import get_db
import models, schemas
router = APIRouter(
prefix="/patients",
tags=["patients"],
responses={404: {"description": "Not found"}}
)
@router.post("/", response_model=schemas.Patient)
def create_patient(patient: schemas.PatientCreate, db: Session = Depends(get_db)):
db_patient = models.Patient(**patient.dict())
db.add(db_patient)
db.commit()
db.refresh(db_patient)
return db_patient
위 코드 중
from fastapi import APIRouter
router = APIRouter(
prefix="/patients",
tags=["patients"],
responses={404: {"description": "Not found"}}
)
이 부분에 대해서 먼저 설명을 하면, router라는 변수 명으로 APIRouter 인스턴스를 생성하게 된다.
인자를 설명하게 된다면,
그렇다면 patient파일이 아닌 다른 파일의 router는 다음과 같이 설정하게 될 것이다.
router = APIRouter(
prefix="/examination",
tags=["exmaination"],
responses={404: {"description" : "Not found"}}
)
이렇게 라우터를 정의한 후에는 main.py에 이를 FastAPI 애플리케이션에 등록해야 함.
해당 부분을 간단하게 본다면
from fastapi import FastAPI
from routers import patients
app = FastAPI(...)
app.include_router(patients.router)
이렇게 할 경우 해당 라우터의 모든 엔드포인트가 활성화된다.
이제 다음 코드를 한 번 살펴보자
@router.post("/", response_model=schemas.Patient)
def create_patient(patient: schemas.PatientCreate, db: Session = Depends(get_db)):
db_patient = models.Patient(**patient.dict())
db.add(db_patient)
db.commit()
db.refresh(db_patient)
return db_patient
이제 여기 설명이 아직 없는 부분들이 있다. database.py는 어떻게 생성하였는지, schemas.py는 어떻게 생성되었는지
해당 부분은 다음 글로 이어서 설명
[FastAPI] FastAPI 내부 코드 확인하기 (FastAPI 클래스 생성자 메소드 debug 인자) (0) | 2025.04.17 |
---|---|
[FastAPI] (STT 기능 API 만들기)음성인식 데이터 처리 (WAV to PCM) #1 (0) | 2025.04.16 |
[FastAPI] CRUD 구현 (models.py 중심) #4 (0) | 2025.04.11 |
[FastAPI] CRUD 구현 (schemas.py 부분) #3 (0) | 2025.04.11 |
[FastAPI] CRUD 구현 (database.py부분 중점) #2 (0) | 2025.04.09 |