1
0

More than 3 years have passed since last update.

pythonのbottleでちょっとしたAPIサーバを作る

Posted at

ちょっとしたAPIサーバがほしいとき、pythonで手軽に作ることができます。

requirements.txt
bottle==0.12.18
app.py
# -*- coding:utf-8 -*-
from bottle import (get, HTTPResponse, default_app)
from wsgiref.simple_server import WSGIServer, make_server
from socketserver import ThreadingMixIn
import json


class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
    """
    マルチスレッドなWSGIServer
    """
    pass

@get('/active')
def is_active():
    return 'OK'

@get('/testget')
def test_get():
    dummy_response = {
        'value': 'test'
    }

    # json形式で返す
    res = HTTPResponse(status=200, body=json.dumps(dummy_response))
    res.set_header('Content-Type', 'application/json')
    res.set_header('Access-Control-Allow-Origin', '*')
    return res

if __name__ == "__main__":
    app = default_app()
    server = make_server('0.0.0.0', 80, app, ThreadingWSGIServer)
    server.serve_forever()

Dockerfile

# docker build
FROM ubuntu:20.04

# python install
RUN apt-get update
RUN apt-get install -y python3 python3-pip

# Install python module
COPY requirements.txt /tmp/requirements.txt

RUN python3 -m pip install -r \
  /tmp/requirements.txt && \
  rm -rf /root/.cache

COPY app.py /var/app/

WORKDIR /var/app/

CMD ["python3", "/var/app/app.py"]

手順

docker build -t test-api .
docker run --rm -itd -p 8888:80 test-api

アクセスしてみる

curl http://localhost:8888/active
curl http://localhost:8888/testget
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0