Quickly implement REST API in Python

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.

environment

Module installation

With Flask, a web application framework Install Peewee of ORM.

$ pip install flask
$ pip install peewee

Data import

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 implementation

API specifications
Function: Get customer information
path: getUser /: userId
method: 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('/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)

Verification

$ 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

Quickly implement REST API in Python
Quickly try Microsoft's Face API in Python
Implement Enigma in python
Implement recommendations in Python
Evernote API in Python
Implement sum in Python
C API in Python 3
Implement Traceroute in Python 3
[WP REST API v2] Upload images in Python
Hit Mastodon's API in Python
Implement ancient ciphers in python
Implement Redis Mutex in Python
Implement extension field in Python
Implement method chain in Python
Blender Python API in Houdini (Python 3)
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
Python beginners tried implementing REST API in one day
Get LEAD data using Marketo's REST API in Python
Implement stacking learning in Python [Kaggle]
Implement R's power.prop.test function in python
Getting the arXiv API in Python
Implement the Singleton pattern in Python
Specification generation and code generation in REST API development (Python edition)
Access the Twitter API in Python
Cloud DevOps Cookbook Part 4-Explore DevOps DirectMail in Python with REST API
I tried to implement PLSA in Python
Mouse operation using Windows API in Python
Try using the Wunderlist API in Python
Implement __eq__ etc. generically in Python class
Try using the Kraken API in Python
Implement FIR filters in Python and C
Collectively implement statistical hypothesis testing in Python
I tried to implement PLSA in Python 2
Tweet using the Twitter API in Python
Get Google Fit API data in Python
[Python] REST API essential, convenient library summary
Get Youtube data in Python using Youtube Data API
I tried to implement ADALINE in Python
I tried to implement PPO in Python
[Python] Quickly create an API with Flask
Try hitting the YouTube API in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
N-Gram in Python
Programming in python
Development and deployment of REST API in Python using Falcon Web Framework
Plink in Python
Constant in python