LoginSignup
246
279

More than 3 years have passed since last update.

PythonでREST APIをサクっと実装

Last updated at Posted at 2016-05-27

勉強会でAPIについて学んだのでPythonで簡単なREST APIを実装してみました.
Pythonのインストール方法などは他で説明されているので割愛します.

環境

  • CentOS 7.0
  • Python 3.5.1
  • SQLite3 3.9.2

モジュールのインストール

ウェブアプリケーションフレームワークのFlaskと
ORMのPeeweeをインストールします.

$ pip install flask
$ pip install peewee

データのインポート

以下の様なデータをデータベースにインポートします.

user.tsv
#userId     userCompany     userDiscountRate
Us0ymuik    密林コンプライアンス印刷    46
Us77qmr2    西日本密林エンターテイメント  49
Usdj7ej1    密林ソリューション 18
Usjx15uh    横浜ヒュージハードソフト    7
Usqd7wpe    面本信金    1
Uswvrn3s    ゴールデンモービルソリューション    7
Us3h2d0a    ベンザソーシャルゲーミングソリューション    26
Usa4c2hm    ヴァーチャウェアソーシャルゲーミング産業    7
.
.
.

Peeweeでデータベースに接続してデータを登録します.

import.py
# -*- coding: utf-8 -*-
import peewee

# データベースを指定
db = peewee.SqliteDatabase("data.db")

# ユーザーモデルを定義
class User(peewee.Model):
    userId = peewee.TextField()
    userCompany = peewee.TextField()
    userDiscountRate = peewee.IntegerField()

    class Meta:
        database = db

# ユーザーテーブル作成
User.create_table()

# tsvファイルを一行ずつ読み込んでタブで分割し,それぞれをデータベースに登録
for line in open("user.tsv", "r"):
    (userId, userCompany, userDiscountRate) = tuple(line[:-1].split("\t"))
    if userDiscountRate.isdigit(): # 一行目のコメント対応.
        User.create(userId = userId,
                    userCompany = userCompany,
                    userDiscountRate = int(userDiscountRate))

APIの実装

API仕様
機能:顧客情報の取得
パス:Users/:userId
メソッド:GET
api.py
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, abort, make_response
import peewee
# import json

db = peewee.SqliteDatabase("data.db")

class User(peewee.Model):
    userId = peewee.TextField()
    userCompany = peewee.TextField()
    userDiscountRate = peewee.IntegerField()

    class Meta:
        database = db

api = Flask(__name__)

@api.route('/Users/<string:userId>', methods=['GET'])
def get_user(userId):
    try:
        user = User.get(User.userId == userId)
    except User.DoesNotExist:
        abort(404)

    result = {
        "result":True,
        "data":{
            "userId":user.userId,
            "userCompany":user.userCompany,
            "userDiscountRate":user.userDiscountRate
            }
        }

    return make_response(jsonify(result))
    # Unicodeにしたくない場合は↓
    # return make_response(json.dumps(result, ensure_ascii=False))

@api.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == '__main__':
    api.run(host='0.0.0.0', port=3000)

確認

$ curl -i http://0.0.0.0:3000/Users/Usdj7ej1
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 118
Server: Werkzeug/0.11.10 Python/3.5.1
Date: Fri, 27 May 2016 06:29:57 GMT

{"data": {"userCompany": "密林ソリューション", "userDiscountRate": 18, "userId": "Usdj7ej1"}, "result": true}%
246
279
2

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
246
279