필요한 라이브러리를 먼저 설치합니다.
pip install fastapi uvicorn
or
pip install "fastapi[all]"
# main.py
from fastapi import FastAPI
app = FastAPI()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
서버 실행을 위한 가장 최소한의 코드입니다.
ASGI인 uvicorn을 통해 앱을 실행하면 됩니다. 코드 수정을 감지해서 바로 서버에 갱신되게 하고 싶다면, reload=True 옵션을 넣어주시면 됩니다.
우선, 폴더구조를 아래와 같이 진행했습니다.
fastapi
├ api
│ └ endpoint.py
├ main.py
└ requirements.txt
# api/endpoint.py
from fastapi import APIRouter
# router를 통해, app에 등록하는 방식
router = APIRouter()
@router.get("/unixtime")
def get_unixtime():
from datetime import datetime, timezone, timedelta
# 한국 시간 (KST) 타임존 설정
kst = timezone(timedelta(hours=9))
unix_time = int(datetime.now(kst).timestamp())
return {
"unixtime": unix_time
}
간단하게 한국 시간대를 기준으로 unixtime을 반환하는 API 코드입니다.
# main.py
from fastapi import FastAPI
from api.unixtime import router as unix_router
app = FastAPI()
# router를 import하고 app에 등록함.
app.include_router(unix_router)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
서버를 실행하고, 요청을 날려보면 정상적으로 작동합니다.

FastAPI는 Swagger를 사용하여 API를 자동으로 문서화합니다.
http://localhost:8000/docs으로 접근하면 생성된 문서를 확인할 수 있습니다.

추가적으로 아래의 글을 읽어보시면, FastAPI의 강력한 기능을 확인할 수 있습니다.