Since I learned about API in the study session, I implemented a simple REST API in Python. How to install Python is explained elsewhere, so I will omit it.
With Flask, a web application framework Install Peewee of ORM.
$ pip install flask
$ pip install peewee
Import the following data into the database.
user.tsv
#userId userCompany userDiscountRate
Us0ymuik Dense Forest Compliance Printing 46
Us77qmr2 West Japan Dense Forest Entertainment 49
Usdj7ej1 jungle solution 18
Usjx15uh Yokohama Huge Hard Software 7
Usqd7wpe Shinkin bank 1
Uswvrn3s Golden Mobile Solution 7
Us3h2d0a Benza Social Gaming Solution 26
Usa4c2hm Virtualware Social Gaming Industry 7
.
.
.
Connect to the database with Peewee and register the data.
import.py
# -*- coding: utf-8 -*-
import peewee
#Specify database
db = peewee.SqliteDatabase("data.db")
#Define user model
class User(peewee.Model):
userId = peewee.TextField()
userCompany = peewee.TextField()
userDiscountRate = peewee.IntegerField()
class Meta:
database = db
#User table creation
User.create_table()
#Read the tsv file line by line, divide it by tabs, and register each in the database
for line in open("user.tsv", "r"):
(userId, userCompany, userDiscountRate) = tuple(line[:-1].split("\t"))
if userDiscountRate.isdigit(): #Supports comments on the first line.
User.create(userId = userId,
userCompany = userCompany,
userDiscountRate = int(userDiscountRate))
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('/getUser/<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))
#If you don't want to use 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/getUser/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": "Dense forest solution", "userDiscountRate": 18, "userId": "Usdj7ej1"}, "result": true}%
Recommended Posts