Python beginners tried implementing REST API in one day

I participated in Nagoya.Swift + May Study Session. This is a summary of what I did.

Background

I usually write Swift, but I was interested in machine learning and so on, so I decided to get used to the Python syntax for the time being, so I implemented a REST API that I have experience in implementing in other languages.

Implementation

Implemented GET by referring to @ Morinikki's Implementing REST API quickly with Python.

Now that I know how to create an endpoint, I'll use POST, PUT, and DELETE as well, and read peewee's Document. I implemented it.

api.py


# -*- coding: utf-8 -*-
from flask import Flask, jsonify, abort, make_response, request
import peewee as pe
import random
import json

#Random string
def random_string(length, seq='0123456789abcdefghijklmnopqrstuvwxyz'):
    sr = random.SystemRandom()
    return ''.join([sr.choice(seq) for i in range(length)])


db = pe.SqliteDatabase("datas.db")

#model
class User(pe.Model):
    userId = pe.TextField()
    name = pe.TextField()
    caption = pe.TextField()
    old = pe.IntegerField()

    class Meta:
        database = db

api = Flask(__name__)

#Get user
@api.route('/user/<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,
            "name":user.name,
            "caption":user.caption,
            "old":int(user.old)
            }
        }

    return make_response(jsonify(result))

#add to
@api.route('/user', methods=['POST'])
def post_user():
    userId = 'us_'+random_string(6)
    dataDict = json.loads(request.data)
    try:
        q = User.insert(userId=userId, name=dataDict["name"], caption=dataDict["caption"], old=dataDict["old"])
        q.execute()  # perform the insert.
        user = User.get(User.userId == userId)
    except User.DoesNotExist:
        abort(404)

    result = {
        "result":True,
        "data":{
            "userId":user.userId,
            "name":user.name,
            "caption":user.caption,
            "old":int(user.old)
            }
        }

    return make_response(jsonify(result))

#update
@api.route('/user/<string:userId>', methods=['PUT'])
def put_user(userId):
    dataDict = json.loads(request.data)
    try:
        q = User.update(name=dataDict["name"], caption=dataDict["caption"], old=dataDict["old"]).where(User.userId == userId)
        q.execute()
    except User.DoesNotExist:
        abort(404)

    result = {
        "result":True
        }

    return make_response(jsonify(result))

#Delete
@api.route('/user/<string:userId>', methods=['DELETE'])
def del_user(userId):
    try:
        q = User.delete().where(User.userId == userId)
        q.execute() 
    except User.DoesNotExist:
        abort(404)

    result = {
        "result":True,
        }

    return make_response(jsonify(result))

#Get all users
@api.route('/users', methods=['GET'])
def get_users():
    try:
        users = User.select()
    except User.DoesNotExist:
        abort(404)

    arr = []
    for user in users:
        arr.append({
            "userId":user.userId,
            "name":user.name,
            "caption":user.caption,
            "old":int(user.old)
            })

    result = {
        "result":True,
        "data":arr
        }

    return make_response(jsonify(result))

@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)

Impressions

It took about 5 hours to implement this. I think it was pretty good for the first Python. However, I didn't write it while understanding it, so it is necessary to deepen my understanding.

After this, it was good to be able to create an iOS client (implementing only GET and DELETE due to time constraints) and demo it in the spare time (I wanted to write Swift somewhere because it was a study session called Nagoya.Swift +).

Recommended Posts

Python beginners tried implementing REST API in one day
Quickly implement REST API in Python
Try implementing two stacks in one array in Python
[WP REST API v2] Upload images in Python
One liner in Python
Evernote API in Python
C API in Python 3
Python beginners tried it in 3 days from OS installation to running Twitter API
Get LEAD data using Marketo's REST API in Python
Hit Mastodon's API in Python
Fizzbuzz in Python (in one line)
DMD in Python one dimension
Try implementing Yubaba in Python 3
Blender Python API in Houdini (Python 3)
I tried to create API list.csv in Python from swagger.yaml
Specification generation and code generation in REST API development (Python edition)
Getting the arXiv API in Python
Hit the Sesami API in Python
Python beginners tried Hello World in 30 seconds using the micro-framework Flask
Try implementing extension method in python
Create Gmail in Python without API
"The one that blocks all Twitter accounts in the database" created by beginners of Python learning day
Hit the web API in Python
Cloud DevOps Cookbook Part 4-Explore DevOps DirectMail in Python with REST API
Implementing a simple algorithm in Python 2
Run unittests in Python (for beginners)
web coder tried excel in Python
Access the Twitter API in Python
I tried Line notification in Python
python beginners tried to find out
Development and deployment of REST API in Python using Falcon Web Framework
Handle multiple python versions in one jupyter
I tried to implement PLSA in Python
Mouse operation using Windows API in Python
CGI server (1) python edition in one line
Try using the Wunderlist API in Python
I tried to implement permutation in Python
Try using the Kraken API in Python
[Episode 2] Beginners tried Numeron AI with python
[Episode 3] Beginners tried Numeron AI with python
I tried to implement PLSA in Python 2
Tweet using the Twitter API in Python
Get Google Fit API data in Python
I tried using Bayesian Optimization in Python
[Python] REST API essential, convenient library summary
Get Youtube data in Python using Youtube Data API
I tried using UnityCloudBuild API from Python
I tried to implement ADALINE in Python
[Episode 0] Beginners tried Numeron AI with python
[Episode 1] Beginners tried Numeron AI with python
Quickly try Microsoft's Face API in Python
One liner webServer (with CGI) in python
I tried to implement PPO in Python
Decompose command arguments in one line in Python
[Python] Invert bool value in one line
Try hitting the YouTube API in Python
Put the exchange rate obtained from Oanda REST API in Python into MongoDB
Python day 1
A machine learning beginner tried to create a sheltie judgment AI in one day
One liner that outputs multiplication tables in Python
3.14 π day, so try to output in Python