본문 바로가기

개발

FastAPI

🍏 FastAPI란

= 파이썬 기반의 웹 프레임워크

 

특징

- 빠르다 = Starlette 및 Uvicorn 기반의 비동기(ASGI) 서버 위에서 동작

- 자동 문서화 = API생성시 Swagger 자동 생성. 

- Restful API나 MSA 등에 적합.

 

🍏 설치

python 3.6 버전 이상에서만 설치 가능

fastapi + pydantic, uvicorn, jinja2, python-multipart 등 부가 패키지를 함께 설치

pip install "fastapi[all]"

 

🍏 기초 예제

+) fast api 공식문서를 참고하여 작성했다.

https://fastapi.tiangolo.com/tutorial/first-steps/

 

First Steps - FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

 

코드

main.py

from fastapi import FastAPI #import fast api
#FastAPI = a Python class that provides all the functionality for your API.

app = FastAPI() #create a FastAPI instance

@app.get("/") #create a path operation
async def root(): # define the path operation function
    return {"message": "Hello World"} # return the content

 

 

실행

python -m fastapi dev main.py

=main.py 단일 파일 실행

 

 

노란 박스 내용으로 local machine에서 돌아가는 내 app URL을 확인할 수 있다

 

 

작동 확인

위에서 확인한 URL로 작동을 확인해보자

http://127.0.0.1:8000/의 화면

 

 

swagger 확인

http://127.0.0.1:8000/docs

 

 

 

🍏 프로젝트 예제

 

fastAPI 프로젝트 구조

fastapi에서는 어떠한 구조로 백엔드 구조를 설계하면 좋을까?

 

https://medium.com/@amirm.lavasani/how-to-structure-your-fastapi-projects-0219a6600a8f

해당 글을 참고했고 아주 간단한 프로젝트를 만들것이라 두번 째 방식을 선택했다.

 

.
├── app
│   ├── __init__.py          # 이 directory가 패키지 일부임을 알리는 역할
│   ├── main.py              # FastAPI 앱 실행
│   ├── routers/
│   │   └── items.py         # CRUD API 라우팅
│   ├── crud/
│   │   └── item.py          # CRUD 로직
│   ├── schemas/
│   │   └── item.py          # Pydantic 모델 : 데이터 유효성 검사 도움
│   ├── models/
│   │   └── item.py          # DB 모델
│   └── utils/
│       └── s3_parquet.py    # S3+Parquet 로딩
├── tests/
│   └── test_items.py
├── requirements.txt         # 필요한 파이썬 패키지 목록
└── README.md                # 프로젝트 설명 문서

 

 

패키지 설치

pip install -r requirements.txt

requirements.txt에 기록해 놓은 설치해야하는 패키지들을 한 번에 설치 가능

 

 

프로젝트 실행

python -m uvicorn app.main:app --reload

= 프로젝트의 app/main.py 안에 있는 FastAPI 인스턴스 실행

 

 

swagger 확인

http://localhost:8000/docs

swagger 결과 예시