앱 확장하기
이 페이지에서는 shop에 /users 리소스를 추가합니다. 처음에는 main.py 하나에 직접 손으로 추가하고, 그다음에는 layered 프로젝트에서 fastkit addroute로 추가합니다. FastAPI가 애플리케이션을 라우터(APIRouter와 include_router)로 나누는 방법, 의존성(Depends)이 엔드포인트에 객체를 전달하는 방법, 설정 값을 환경 변수와 .env에서 읽어 오는 방법, 그리고 CORS 미들웨어가 하는 일을 배웁니다.
/users 직접 추가하기
엔드포인트를 가장 빨리 추가하는 방법은 이미 동작하는 엔드포인트를 복사하는 것입니다. 생성하기에서 만든 hello 프로젝트에서 Item 모델과 아이템 엔드포인트 두 개를 main.py의 끝에 복사하고, 사용자에 맞게 이름을 바꿉니다.
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str = Field(min_length=3, max_length=254)
class StoredUser(User):
id: int
users: dict[int, StoredUser] = {}
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: User) -> StoredUser:
stored = StoredUser(id=len(users) + 1, **user.model_dump())
users[stored.id] = stored
return stored
@app.get("/users/{user_id}")
async def read_user(user_id: int) -> StoredUser:
if user_id not in users:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
return users[user_id]
tests/test_main.py에서는 import 문을 from main import app, items, users로 바꾸고, empty_store 픽스처에 있는 각 items.clear() 뒤에 users.clear()를 추가합니다. 그리고 파일 끝에 테스트 두 개를 추가합니다.
ADA = {"name": "Ada", "email": "ada@example.com"}
def test_create_user_returns_it_with_a_new_id() -> None:
response = client.post("/users", json=ADA)
assert response.status_code == 201
assert response.json() == {**ADA, "id": 1}
def test_read_user_that_does_not_exist() -> None:
response = client.get("/users/42")
assert response.status_code == 404
assert response.json() == {"detail": "User not found"}
파일 하나로 부족해질 때
fastkit addroute는 리소스를 대신 추가해 주지만, 새 모듈을 넣을 패키지가 있어야 동작합니다. hello 프로젝트에서는 이 명령이 리소스 추가를 거부하고 그 이유를 알려 줍니다.
$ fastkit addroute users .
╭───────────────────────────────── Error ──────────────────────────────────╮
│ ❌ This project keeps its whole application in main.py, so there is no │
│ package to add route modules to. Add the endpoint to main.py by hand, │
│ next to the existing ones (copy one endpoint and its test), or create a │
│ project at a later level with `fastkit init --level layered` (`fastkit │
│ list-templates` lists the templates). │
╰──────────────────────────────────────────────────────────────────────────╯
layered 레벨은 애플리케이션을 라우트, 데이터 접근(crud), 스키마, 코어 설정 패키지로 나눕니다. fastkit은 기존 프로젝트를 다른 레벨로 변환하지 않으므로, hello 프로젝트 폴더 바깥에 새 프로젝트를 만듭니다(그 위치에 shop 폴더가 아직 없어야 합니다). -y를 지정하면 질문 없이 모든 기본값을 받아들입니다.
$ fastkit init --level layered --name shop -y
...
$ cd shop
$ find src -name '*.py' -not -name '__init__.py' | sort
src/api/api.py
src/api/deps.py
src/api/routes/items.py
src/core/config.py
src/core/pagination.py
src/core/responses.py
src/crud/items.py
src/main.py
src/schemas/items.py
이제 아이템은 src/mocks/mock_items.json 파일에 저장되므로 서버를 다시 시작해도 사라지지 않습니다. 또한 모든 엔드포인트는 /api/v1/items처럼 /api/v1 아래에 있습니다.
라우터와 의존성
APIRouter는 별도의 모듈에 작성하는 경로 작동의 묶음이며, @app.get(...) 대신 @router.get(...)을 사용합니다. src/api/routes/items.py는 APIRouter(prefix="/items", tags=["items"])로 라우터를 하나 만들고, 이 접두사와 태그는 라우터에 속한 모든 엔드포인트에 적용됩니다. include_router는 한 라우터의 엔드포인트를 다른 라우터나 앱에 추가합니다. src/api/api.py는 모든 리소스의 라우터를 한곳에 모읍니다.
# One APIRouter collects the routers of every module; main.py mounts it once.
# https://fastapi.tiangolo.com/tutorial/bigger-applications/
api_router = APIRouter()
api_router.include_router(items.router)
# fastkit:routes
그다음 src/main.py가 app.include_router(api_router, prefix=settings.API_V1_PREFIX)로 이 라우터를 한 번 마운트합니다. 두 파일에 있는 # fastkit:imports와 # fastkit:routes 주석은 fastkit addroute가 코드 줄을 추가할 위치를 표시하므로 지우지 말고 그대로 두세요.
의존성은 FastAPI가 엔드포인트보다 먼저 호출하는 함수이며, 엔드포인트는 이 함수가 반환한 값을 받습니다. 의존성은 Depends(...)로 선언하고, Annotated 별칭을 만들어 두면 모든 엔드포인트에서 재사용할 수 있습니다.
def get_item_store() -> ItemStore:
"""Return the item store (tests override this dependency)."""
return item_store
# ...
ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)]
각 아이템 엔드포인트는 def get_item(item_id: int, store: ItemStoreDep) -> ItemRead처럼 store: ItemStoreDep를 선언합니다. 어떤 엔드포인트도 저장소를 직접 만들지 않기 때문에, 테스트에서는 get_item_store를 테스트 전용 저장소로 바꿔 끼울 수 있습니다(방법은 앱 테스트하기에서 설명합니다).
설정과 CORS
설정은 시크릿 키나 허용할 출처처럼 실행하는 머신마다 달라지는 값입니다. pydantic-settings의 BaseSettings 클래스는 각 필드의 값을 이름이 같은 환경 변수나 .env 파일에서 읽고, 둘 다 없으면 기본값을 사용합니다.
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_ignore_empty=True,
extra="ignore",
)
fastkit은 고유한 SECRET_KEY를 넣어 .env를 작성했습니다. Git은 .env를 무시하며, .env.example에는 다음 사람을 위해 모든 설정 항목이 나열되어 있습니다. 그중 하나가 BACKEND_CORS_ORIGINS입니다. 다른 출처(스킴, 호스트, 포트)의 웹 페이지가 API를 호출하면, 브라우저는 API가 보낸 CORS 헤더를 읽고 그 페이지가 응답을 읽어도 되는지 판단합니다. CORS 미들웨어는 .env의 BACKEND_CORS_ORIGINS=http://localhost:3000처럼 지정한 출처에 대해 이 헤더를 보냅니다. src/main.py는 이 목록이 비어 있지 않을 때만 CORS 미들웨어를 설치합니다. CORS는 인증 수단이 아닙니다. curl이나 다른 서버 같은 클라이언트가 API를 호출하는 것은 막지 못합니다.
fastkit으로 사용자 리소스 추가하기
--dry-run을 지정하면 fastkit addroute가 작성할 파일 목록만 보여 주고, --diff를 지정하면 각 변경 내용도 함께 출력합니다.
$ fastkit addroute users . --dry-run
...
Files to create (4):
+ src/api/routes/users.py
+ src/crud/users.py
+ src/schemas/users.py
+ tests/test_users.py
Files to modify (2):
~ src/api/deps.py
~ src/api/api.py
...
--dry-run 없이 다시 실행하고 확인합니다. 새 리소스에는 /api/v1/users 아래에 페이지네이션이 적용된 목록 조회, 생성(201), 단건 조회, 교체(PUT), 수정(PATCH), 삭제(204) 엔드포인트가 있으며, 각 엔드포인트의 테스트도 함께 생성됩니다. 스키마에는 처음부터 name과 description 필드가 들어 있습니다. 원하는 필드를 넣으려면 src/schemas/users.py를 수정하세요. src/api/api.py에는 두 표시 주석 아래에 라우터의 import 문과 include_router 줄이 추가되고, src/api/deps.py에는 새 의존성 별칭이 추가됩니다. 이 별칭은 src/api/routes/users.py가 import해서 사용합니다.
from src.crud.users import UserRepository, get_user_repository
# ...
UserRepositoryDep = Annotated[UserRepository, Depends(get_user_repository)]
이제 uv run pytest -q를 실행하면 91 passed가 출력됩니다. 프로젝트에 원래 들어 있던 테스트 74개와 tests/test_users.py에 새로 추가된 테스트 17개를 합한 결과입니다.
hello와 layered 사이에는 single-file 레벨이 있습니다. 이 레벨에서는 애플리케이션 전체가 src/main.py 하나에 들어 있으며, 설정과 테스트도 제공됩니다. 이 레벨에서 fastkit addroute를 처음 사용하면 src/main.py 주위에 api, crud, schemas, core 패키지가 추가됩니다.
FastAPI 문서
다음 단계
앱 테스트하기에서는 계층형 프로젝트의 테스트를 읽고 새 테스트를 직접 작성합니다.