-FastAPI란 무엇인가
1. FastAPI란?
FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크이다.
FastAPI는 다음과 같은 특징을 가진다
- 빠름: (Starlette과 Pydantic 덕분에) NodeJS 및 Go와 대등할 정도로 매우 높은 성능. 사용 가능한 가장 빠른 파이썬 프레임워크 중 하나.
- 빠른 코드 작성: 약 200%에서 300%까지 기능 개발 속도 증가.
- 적은 버그: 사람(개발자)에 의한 에러 약 40% 감소.
- 직관적: 훌륭한 편집기 지원. 모든 곳에서 자동완성. 적은 디버깅 시간.
- 쉬움: 쉽게 사용하고 배우도록 설계. 적은 문서 읽기 시간.
- 짧음: 코드 중복 최소화. 각 매개변수 선언의 여러 기능. 적은 버그.
- 견고함: 준비된 프로덕션 용 코드를 얻으십시오. 자동 대화형 문서와 함께.
- 표준 기반: API에 대한 (완전히 호환되는) 개방형 표준 기반: OpenAPI (이전에 Swagger로 알려졌던) 및 JSON 스키마.
2. FastAPI의 디렉토리 구조
적절한 프로젝트 구조화는 프로젝트 확장을 용이하게 하고, 유지보수성이 향상되며, 명확한 구조로 인해 협업이 수월해진다는 측면에서 매우 중요합니다.
이러한 이점을 챙기기 위해서 프로젝트 구조화를 하려 한다면 다음과 같은 원칙을 지켜야 합니다.
- 관심사 분리 : FastAPI의 다양한 측면을 성질에 따라 구분하여 코드 가독성과 유지보수를 향상 (ex. routes, models, service)
- 모듈화 : 재사용 가능한 모듈로 나눔
- 의존성 주입 : 의존성 주입을 사용해 구성 요소 분리 (ex. fastapi.Depends)
- 테스트 가능성 : mocking 등의 전략을 사용해 테스트 가능하도록 설계
이와 같은 원칙에 따라 다음과 같은 구조들로 프로젝트를 빌드할 수 있다.
- 파일 유형에 따른 구조화
이 방식은 파일의 역할이나 계층(ex. 데이터베이스, 서비스, 컨트롤러)에 따라 파일을 분류하는 것이다. 파이썬에서는 API, CRUD, models 등의 유형으로 나뉠 수 있다. 각각의 디렉토리 내의 파일에서 볼 수 있는 스코프가 매우 작으므로 MSA 프로그램에 적합한 구조이다.├── app # Contains the main application files. │ ├── __init__.py # this file makes "app" a "Python package" │ ├── main.py # Initializes the FastAPI application. │ ├── dependencies.py # Defines dependencies used by the routers │ ├── routers │ │ ├── __init__.py │ │ ├── items.py # Defines routes and endpoints related to items. │ │ └── users.py # Defines routes and endpoints related to users. │ ├── crud │ │ ├── __init__.py │ │ ├── item.py # Defines CRUD operations for items. │ │ └── user.py # Defines CRUD operations for users. │ ├── schemas │ │ ├── __init__.py │ │ ├── item.py # Defines schemas for items. │ │ └── user.py # Defines schemas for users. │ ├── models │ │ ├── __init__.py │ │ ├── item.py # Defines database models for items. │ │ └── user.py # Defines database models for users. │ ├── external_services │ │ ├── __init__.py │ │ ├── email.py # Defines functions for sending emails. │ │ └── notification.py # Defines functions for sending notifications │ └── utils │ ├── __init__.py │ ├── authentication.py # Defines functions for authentication. │ └── validation.py # Defines functions for validation. ├── tests │ ├── __init__.py │ ├── test_main.py │ ├── test_items.py # Tests for the items module. │ └── test_users.py # Tests for the users module. ├── requirements.txt ├── .gitignore └── README.md
- 모듈의 기능에 따른 구조화
이 접근 방법은 패키지의 기능에 따라 디렉토리를 구조화하는 것이다. 하나의 하위 패키지에 필요한 모든 파일의 유형을 그룹화하여 개발 효율성을 높일 수 있으므로 모놀리식 프로젝트에 적합하다. 이러한 구조에서 각각의 패키지는 모두 각가의 router, schema, model 등을 가진다.fastapi-project ├── alembic/ ├── src │ ├── auth │ │ ├── router.py # auth main router with all the endpoints │ │ ├── schemas.py # pydantic models │ │ ├── models.py # database models │ │ ├── dependencies.py # router dependencies │ │ ├── config.py # local configs │ │ ├── constants.py # module-specific constants │ │ ├── exceptions.py # module-specific errors │ │ ├── service.py # module-specific business logic │ │ └── utils.py # any other non-business logic functions │ ├── aws │ │ ├── client.py # client model for external service communication │ │ ├── schemas.py │ │ ├── config.py │ │ ├── constants.py │ │ ├── exceptions.py │ │ └── utils.py │ └── posts │ │ ├── router.py │ │ ├── schemas.py │ │ ├── models.py │ │ ├── dependencies.py │ │ ├── constants.py │ │ ├── exceptions.py │ │ ├── service.py │ │ └── utils.py │ ├── config.py # global configs │ ├── models.py # global database models │ ├── exceptions.py # global exceptions │ ├── pagination.py # global module e.g. pagination │ ├── database.py # db connection related stuff │ └── main.py ├── tests/ │ ├── auth │ ├── aws │ └── posts ├── templates/ │ └── index.html ├── requirements │ ├── base.txt │ ├── dev.txt │ └── prod.txt ├── .env ├── .gitignore ├── logging.ini └── alembic.ini
참고
- https://fastapi.tiangolo.com/ko/
- https://medium.com/@amirm.lavasani/how-to-structure-your-fastapi-projects-0219a6600a8f