Fast API 기초
개요
프레임워크 중 하나인 FastAPI. 데이터베이스에서의 생성(Create), 읽기(Read), 갱신(Update), 삭제(Delete) 작업인 CRUD를 손쉽게 처리할 수 있다. 서버 실행 시에는 Gunicorn(Green Unicorn)과 같은 ASGI (Asynchronous Server Gateway Interface) 서버를 이용할 것이다.
설치
pip install "fastapi[all]"
서버 실행
main.py 파일을 생성한 후 해당 경로에서 아래의 명령어를 실행
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
uvicorn main:app --reload
경로 매개변수
파이썬 포맷 문자열이 사용하는 동일한 문법으로 매개변수 또는 변수를 경로에 선언할 수 있다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
Swagger
http://127.0.0.1:8000/docs 주소로 접속을 할 경우 API 문서를 확인할 수 있다.
(FastAPI의 고유 기능이 아닌 다른 프레임워크에서도 지원해 준다)
Pydantic (aka. DTO)
Pydantic은 FastAPI의 DTO(Data Transfer Object) 역할을 한다.
from pydantic import BaseModel
from datetime import date
def main(user_id: str):
return user_id
# A Pydantic mode
class User(BaseModel):
id: int
name: str
joined: date
Pydantic은 주로 데이터 유효성 검사와 파싱을 위해 사용되는 파이썬 라이브러리이다. 데이터의 형식, 제약 조건 및 구조를 정의하고 유지하는 데 도움을 주며, 입력 데이터의 유효성을 검사하여 해당 데이터가 정의한 형식과 제약 조건을 준수하는지 확인할 수 있다.
본 후기는 정보통신산업진흥원(NIPA)에서 주관하는 <AI 서비스 완성! AI+웹개발 취업캠프 - 프런트엔드&백엔드> 과정 학습/프로젝트/과제 기록으로 작성되었습니다.