본문 바로가기

개발이야기/Python

정말 빠른 Fast API

728x90

Introduction

비교적 새로운 Python back-end framework 인 FastAPI에 대해 소개하고자 한다.

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

위 문구는 FastAPI Official page에 적혀있는 문구 이다.

말그대로 FastAPI는 고성능에 배우기 쉽고 작성하기 쉬운 production에 사용이 준비된 framework이다.

 

실제로 node.js 나 golang으로 작성된 서버와 비슷한 수준의 성능과 안정성을 자랑한다고 한다.

그리고 무려 FastAPI는 자동으로 Swagger document를 생성해준다.

 

그럼 한번 설치 해보자.

 

How to install

FastAPI는 Python 3.6 부터 적용된 Type hinting을 사용하기 때문에 Python3.6 이상이 설치되어야 한다.

pip 로 설치 해보자.

pip install fastapi uvicorn

FastAPI를 설치하기 위해서는 fastapi, uvicorn 두개의 package 를 설치해야 한다.

 

Try Hello World

이제 설치도 다 되었으니, Hello world 를 찍어보자.

먼저 아래와 같이 main.py를 작성해보자

 

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def helloworld():
    return {'message':'Hello World'}

 

실행은 아래와 같이 하면 된다.

$ uvicorn main:app --reload
INFO: Will watch for changes in these directories: ['/home/tj/workspace/fastapi_exam']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [10267] using StatReload
INFO: Started server process [10269] INFO: Waiting for application startup.
INFO: Application startup complete.

실행 후에 http://127.0.0.1:8000에 접속하면 위와 같이 Hello World 응답이 출력되는 것을 확인 할 수 있다.

여기서 아래 URL에 접속해보자.

몇 줄 적지도 않았느데 무려 swagger document를 자동으로 생성 해준다.

당연히 아까 작성했던 Hello World도 확인이 가능하다.

 

다음 편에서는 새로운 경로도 생성해보고 어떤 기능들이 있는지 살펴보도록 하겠다.