Python 웹 어플리케이션 프레임워크인 Flask를 이용해 빠르게 REST-ful API 서버를 만들어 보고 Swagger UI documentation을 제공하는 방법을 알아보자.

Flask란?

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

개발

환경 및 주요 패키지

Python 3.x

virtualenv, virtualenvwrapper

Flask-RESTPlus

Flask-RESTPlus is an extension for Flask that adds support for quickly building REST APIs

Flask-RESTPlus 와 유사한 Flask-Restful 이 있는데 Flask-RESTPlus 는 Flask-Restful 을 fork 하여 시작된 프로젝트라고 한다.

Flask-RESTPlus 는 기본적으로 Swagger UI documentation을 제공한다.

설치

1
pip install flask-restplus

Gunicorn

Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX

Flask 에는 Gunicorn을 별도로 설치하지 않아도 built-in 서버가 존재한다. 로컬에서 개발할 때에는 해당 서버를 이용해도 됨.

잠깐 알고가기

패키지 리스트 저장

1
pip freeze > requirements.txt

패키지 설치

1
pip install -r requirements.txt

프로젝트 구조 설계

1
2
3
4
5
6
7
8
projectname
-- api
-- environment
-- server
-- services
run.py
Dockerfile
requirements.txt
  • run.py API Entry Point 에 대한 정의
  • environment profile 에 따른 환경변수에 대한 설정 정의

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import os

    env = os.environ.get("PROFILES_ACTIVE", "local")
    port = os.environ.get("PORT", 8080)

    profiles = {
    "local": {"port": 8080, "debug": True, "swagger-url": "/api/swagger"},
    "dev": {"port": port, "debug": False, "swagger-url": "/api/swagger"}
    }

    environment_config = profiles[env]
  • server flask와 flask-restplus의 서버 인스턴스에 대한 정의 및 설정 (app, api)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    from flask import Flask, request
    from flask_restplus import Api, Resource, fields
    from environment.instance import environment_config
    from time import strftime


    class Server(object):
    def __init__(self):
    self.app = Flask(__name__)
    self.api = Api(self.app,
    version='1.0',
    title='Flask API',
    description='Flask API',
    doc=environment_config["swagger-url"],
    prefix='/api'
    )

    def run(self):
    self.app.run(
    debug=environment_config["debug"],
    port=environment_config["port"]
    )


    server = Server()

    environment_config["swagger-url"] Swagger UI 의 URL path를 정의한다.

  • api API Endpoint 에 매핑되는 Class 정의.

    URI : prefix + namespace + endpoint

GET /api/test/list

1
2
3
4
5
6
7
8
9
10
11
12
test_api = api.namespace('test', description='Test API')
...
@test_api.route('/list')
class TestListAll(Resource):
@test_api.doc('test_list_all')
def get(self):
"""
테스트 목록 조회
"""
test_list = test_service.get_list(is_all=True)
return test_list
...

POST /api/test/create

1
2
3
4
5
@test_api.route('/create')
class TestCreate(Resource):
@test_api.expect(test, validate=True)
def post(self):
...

Parameter 사용 /api/test/{test_id}/update

1
2
3
@test_api.route('/<string:test_id>/update')
class TestUpdate(Resource):
...
  • services service 정의.

Docker를 이용하여 컨테이너화 해보기

Dockerfile

1
2
3
4
5
6
7
8
FROM python:3.7
RUN apt-get update
RUN apt-get install -y gunicorn

COPY . /app
WORKDIR /app
RUN pip install --no-cache-dir -r requirements.txt
ENTRYPOINT ["gunicorn", "-b", "0.0.0.0:8080", "--access-logfile", "access.log", "--error-logfile", "error.log", "run:app"]

이미지 빌드

1
docker build -t flask-test-app:latest .

컨테이너 생성

1
docker run -t -d -p 8080:8080 --name flask-test-app flask-test-app:latest

간단하게 API 서버를 구성해볼 수 있고, 관련 API 문서(Swagger UI documentation)도 만들 수 있다.