로메오의 블로그

FastAPI 서버 구축 본문

Backend/Python & Blockchain

FastAPI 서버 구축

romeoh 2025. 5. 19. 10:30
반응형

버전확인

$ python3 --version
Python 3.11.2

 

 

가상환경구축

$ python3 -m venv myproject
$ source myproject/bin/activate    ## 가상환경 진입
$ deactivate                       ## 가상환경 종료

 

 

 

fastapi 설치

$ pip install fastapi uvicorn

 

Uvicorn: fastapi 실행도구

 

 

 

코드작성

$ cd myproject
$ touch main.py

 

 

 

main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def road_root():
  return {"message": "Hello, FastAPI!"}

 

 

 

서버실행

$ uvicorn main:app --reload

 

 

브라우저 접속

http://localhost:8000/

 

 

 

Swagger 문서

http://localhost:8000/docs

 

 

 

 

 

 

 

 

router 설정

$ mkdir routers
$ touch routers/users.py

 

 

 

 

main.py

from fastapi import FastAPI
from routers import users

app = FastAPI()

app.include_router(users.router)

 

users.py

from fastapi import APIRouter

router = APIRouter(
  prefix="/users",
  tags=["users"],
)

@router.get("/")
def get_users():
  return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

@router.get("/{user_id}")
def get_user(user_id: int):
  return {"id": user_id, "name": f"User{user_id}"}

 

 

 

 

http://localhost:8000/users/

 

 

 

 

 

http://localhost:8000/users/2

 

 

 

 

 

Swagger 문서

http://localhost:8000/docs

 

 

 

 

Pydantic 설정

$ mkdir schemas
$ touch schemas/user.py

 

 

schemas/user.py

# schemas/user.py
from pydantic import BaseModel

class User(BaseModel):
  id: int
  name: str

 

 

 

routers/users.py

from fastapi import APIRouter
from typing import List
from schemas.user import User

router = APIRouter(
  prefix="/users",
  tags=["users"],
)

@router.get("/", response_model=List[User])
def get_users():
  return [
    {"id": 1, "name": "Alice"}, 
    {"id": 2, "name": "Bob"}
  ]

@router.get("/{user_id}", response_model=User)
def get_user(user_id: int):
  return {"id": user_id, "name": f"User{user_id}"}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형
Comments