몰입캠프 3주차를 위한 FastAPI 문법 속성으로 공부하기
가장 기초적인 형태
@app.get("/") 같은 데코레이터가 이 주소로 오면 아래 함수를 실행해라고 알려줌
from fastapi import FastAPI
app = FastAPI()
# GET 요청을 받음
@app.get("/")
async def read_root():
return {"message": "Hello World"}
async def: 비동기 함수로 정의{})를 리턴하면 자동으로 JSON으로 변환되어 나감URL 경로 자체에 들어있는 변수를 받음
예: /items/5 -> item_id는 5
@app.get("/items/{item_id}")
async def read_item(item_id: int): # 타입 힌트(int) 필수!
return {"item_id": item_id}
item_id: int: 이렇게 타입을 적어두면, 사용자가 /items/foo라고 문자를 넣었을 때 FastAPI가 알아서 숫자만 넣으라고 에러를 냄URL 뒤에 ?로 붙는 변수
경로({})에 없는 변수를 함수 인자로 넣으면 자동으로 쿼리 파라미터가 됌
예: /items/?skip=0&limit=10
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
skip: int = 0: 값이 안 들어오면 기본값 0 사용POST 요청으로 복잡한 데이터를 받을 때 사용
Pydantic이라는 라이브러리로 데이터의 모양(스키마)을 정의
from pydantic import BaseModel
# 1. 데이터 모양 정의 (붕어빵 틀)
class Item(BaseModel):
name: str
price: float
is_offer: bool = None # 선택 사항
# 2. 함수에서 사용
@app.post("/items/")
async def create_item(item: Item): # item 변수는 Item 클래스 모양이어야 함
return {"name": item.name, "price": item.price}
Item 클래스 모양과 맞는지 검사하고, 자동으로 변수(item)에 넣어줌item.name처럼 점(.)을 찍어서 데이터에 접근할 수 있음기능별로 파일을 쪼갤 때 사용
파일: `users.py`
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/")
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]
파일: main.py (메인)
from fastapi import FastAPI
from . import users # users.py 불러오기
app = FastAPI()
# users의 라우터를 메인에 합체!
app.include_router(users.router)
FastAPI의 가장 큰 장점
코드를 짜고 서버를 켜면, 자동으로 API 설명서 사이트를 만들어줌
http://localhost:8000/docs