일하는/Cloud, Web

Fast API

김논리 2021. 2. 3. 14:34

fastapi.tiangolo.com

 

FastAPI

FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https://github.com/tiangolo/fastapi FastAPI is a modern, fast (high-performance), web framework for buil

fastapi.tiangolo.com

FastAPI는 Python 기반으로 Flask와 같은 개발 편의성에 NodeJS, Go와 같은 성능과 안정성을 갖춘 Web Framework이다.

공식 페이지에서 언급하는 Key Feature는 다음과 같다.

  • Fast / Fast to code / Fewer bugs / Intuitive / Easy / Short / Robust / Standards-based

특징은 다음과 같다.

  • Starlette 프레임워크를 기반으로 한 비동기 API 서버 지원
  • Pydantic을 사용한 Data validation 지원
  • API Swagger, ReDoc 등을 사용한 API document 자동 생성 지원
  • NodeJS, Go와 대등할 정도로 매우 높은 성능
  • Python3.6+ Type Hinting 지원

Installation

다음 명령어를 이용해 fastapi를 설치할 수 있다.

$ pip install fastapi

또한 웹 서버로 사용될 uvicorn 도 설치한다.

$ pip install uvicorn
uvicornUvloophttptools를 기반으로 구축된 ASGI 서버이다. 자세한 내용은 Uvicorn 공식 페이지를 참조한다.

First Steps

main.py 파일을 생성하여 아래 코드를 작성한다.

from fastapi import FastAPI             # import FastAPI

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

이제 작성된 코드를 서버로 실행해 보자. 명령어는 다음과 같다.

$ uvicorn main:app --reload
  • main : main.py 를 의미한다.
  • app : main.pyapp = FastAPI() 를 의미한다.
  • --reload : 코드 변경 시 자동으로 저장되어 서버가 재시작된다.

다양한 client tool 혹은 브라우저를 이용하여 http://127.0.0.1:8000 으로 접속하면, 아래와 같은 JSON 형식의 Response가 수신됨을 확인할 수 있다.

{
  "message": "Hello World"
}

Interactive API docs

브라우저를 이용하여 http://127.0.0.1:8000/docs 로 접속하면, 아래와 같이 Swagger UI로 자동 생성된 API document 페이지를 확인할 수 있다.

http://127.0.0.1:8000/redoc 으로 접속하면, ReDoc으로 자동 생성된 API document 페이지를 확인할 수 있다.

또한 http://127.0.0.1:8000/openapi.json 으로 접속하면, 아래와 같이 OpenAPI standard에 따른 API 정의 명세를 확인할 수 있다.

{
  "openapi": "3.0.2",
  "info": {
    "title": "FastAPI",
    "version": "0.1.0"
  },
  "paths": {
    "/": {
      "get": {
        "summary": "Root",
        "operationId": "root__get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    }
  }
}