WebApi creation with Python (CRUD creation) For beginners

Purpose of this article

Create a web server that can perform CRUD operations on the DB. I explained it carefully. We welcome you.

Introduction & Premise

○ Premise -Create a list type as a temporary DB and perform CRUD operations on it. I think you should rewrite the operation for the temporary DB to the operation for the actual DB. -It is assumed that python and pip (python package manager) are installed. ○ Introduction As a motivation to create webApi with python, ・ Because I want to use the numpy library to handle DB data mathematically However, when I investigated later, it was faster to leave the web communication itself to js etc. and leave only the data processing to python + numpy. Reference: https://qiita.com/KatsunoriNakamura/items/dd567ea7cfaa99685453

word

-Flask: A web application framework that runs on python. I was able to easily create a web application. -WebApi: In this article, it refers to the web server that operates the DB when you hit the URI.

Overview

  1. Install Flask
  2. Create API file

1. Install Flask

From the command line, type the following command.

pip install Flask

2. Create API file

As a flow of explanation, we will first show the entire code and then briefly explain each code.

Full picture of webAPI file

Create and execute the following file to start the server. You can operate the DB by hitting the URI set in the CRUD method while the server is starting.

sampleapp.py


from flask import Flask, jsonify, request, render_template

app = Flask(__name__)

# DB
stores = [
    {
        'name': 'my_store',
        'items': [
            {
            'name': 'chocolate',
            'price': 120
            }
        ]
    }
]

#CRUD for store--------------
# GET /store/<string:name>
@app.route('/stores/<string:name>') # 'http://127.0.0.1:5000/store/some_name'
def get_store(name):
    for store in stores:
        if store["name"] == name:
            return jsonify(store)
    return jsonify({"message": "no store named {} found.".format(name)})

# POST /store data: {name:}
@app.route('/stores', methods=['POST'])
def create_store():
    request_data = request.get_json()
    store = next(filter(lambda x: x["name"]==request_data["name"], stores), None)
    if store != None:
        return jsonify({"message": "store named {} already exist.".format(request_data["name"])})
    else:
        new_store = {
            "name": request_data["name"],
            "items": request_data["items"]
        }
        stores.append(new_store)
        return jsonify({"message": "{} store is added.".format(request_data["name"])})

# PUT /store data: {name:}
@app.route('/stores/<string:name>', methods=['PUT'])
def update_store(name):
    request_data = request.get_json()
    store = next(filter(lambda x: x["name"] == name, stores), None)
    if store == None:
        return jsonify({"message": "no store named {} found.".format(name)})
    else:
        store["items"] = request_data["items"]
        return jsonify({"message": "{} is updated.".format(name)})

# DELETE /stores/<string:name>
@app.route('/stores/<string:name>', methods=['DELETE'])
def delete_store(name):
    global stores
    stores = list(filter(lambda x: x["name"] != name, stores))
    return jsonify({"message": "Delete store named {}".format(name)})

# --------------------CRUD for store

# GET /stores
@app.route('/stores')
def get_stores():
    return jsonify({'stores': stores})

#Try loading html on the home screen.
# GET /
@app.route('/')
def home():
    return render_template("index.html")

app.run(port=5000)

Commentary

sampleapp.py


from flask import Flask, jsonify, request, render_template

I'm importing the required modules from the Flask library.

sampleapp.py


app = Flask(__name__)

Create the application body. In python, there is a special default variable surrounded by underscores, and name corresponds to the file name, so in this case it corresponds to sampleapp. However, the name of the executable file (the file executed by python ~ from the terminal) returns main. Flask can only work properly on the executable, so I'm making sure name = main for the called file.

sampleapp.py


# DB
stores = [
    {
        'name': 'my_store',
        'items': [
            {
            'name': 'chocolate',
            'price': 120
            }
        ]
    }
]

It is a temporary DB. It is assumed that multiple stores are stored, and each store contains a store name and multiple product data.

sampleapp.py


# GET /store/<string:name>
@app.route('/stores/<string:name>') # 'http://127.0.0.1:5000/store/some_name'
def get_store(name):
    for store in stores:
        if store["name"] == name:
            return jsonify({"stores": store})
    return jsonify({"message": "no store named {} found.".format(name)})

GET method. Specify the store name and return it as a json type response if it exists. Even if the store does not exist, the message is returned as a json type response.

The URI is registered in app with @ app.route ('/ stores / << string: name >>'). (The default IP is automatically specified as'http://127.0.0.1:5000'.) When this URI is hit, the method below will be called. The << string: name >> in the URI is assigned to the argument. jsonify () is a method to create a json type from a dictionary type.

sampleapp.py


# POST /store data: {name:}
def create_store():
    request_data = request.get_json()
    store = next(filter(lambda x: x["name"]==request_data["name"], stores), None)
    if store != None:
        return jsonify({"message": "store named {} already exist.".format(request_data["name"])})
    else:
        new_store = {
            "name": request_data["name"],
            "items": request_data["items"]
        }
        stores.append(new_store)
        return jsonify({"message": "{} store is added.".format(request_data["name"])})

This is the POST method. POST is specified when specifying the URI. (GET is specified by default.) You can get the request body with request.get_json (). If there is no store with the same name, add the store with the request body data to the database.

I will omit the PUT method and DELETE method because there is no additional information.

sampleapp.py


# GET /stores
@app.route('/stores')
def get_stores():
    return jsonify({'stores': stores})

I have created an API to get the entire DB for checking CRUD operations.

sampleapp.py


#Try loading html on the home screen.
# GET /
@app.route('/')
def home():
    return render_template("index.html")

You can call an html file. The callee is set to call the GET method for the entire DB. スクリーンショット 2020-10-06 1.45.12.png

sampleapp.py


app.run(port=5000)

Finally, write the description to start the application. The default 5000 is the default even if you do not specify the port number, but I am writing it for the sake of clarity. Of course, you can specify other port numbers as well.

Operation check

Run

$ python sampleapp.py
 * Serving Flask app "sampleapp" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Verification

I checked using Postman (a tool that makes HTTP requests easy). I was able to confirm the operation of CRUDapi.

GET (stores) Get data for the entire stores スクリーンショット 2020-10-05 23.49.29.png

POST Register the new store by putting it in the quest body. スクリーンショット 2020-10-06 0.15.22.png Confirmation (GET (stores)) スクリーンショット 2020-10-06 0.15.41.png

Home Screen

スクリーンショット 2020-10-06 0.25.41.png

Other CRUDs work as well.

Impressions

If you use python / Flask, It seems that you can create a web API with simple code in a short time.

I will not use it for the original purpose, so I would like to mourn it as a bot webApi.

Recommended Posts

WebApi creation with Python (CRUD creation) For beginners
INSERT into MySQL with Python [For beginners]
[Python] Read images with OpenCV (for beginners)
[For beginners] Try web scraping with Python
python textbook for beginners
OpenCV for Python beginners
Causal reasoning and causal search with Python (for beginners)
~ Tips for Python beginners from Pythonista with love ① ~
~ Tips for Python beginners from Pythonista with love ② ~
[Introduction for beginners] Working with MySQL in Python
Python3 environment construction (for beginners)
Basic Python grammar for beginners
100 Pandas knocks for Python beginners
Python for super beginners Python #functions 1
Python #list for super beginners
~ Tips for beginners to Python ③ ~
[For beginners] Summary of standard input in Python (with explanation)
[Python] Introduction to graph creation using coronavirus data [For beginners]
Solve AtCoder Problems Boot camp for Beginners (Medium 100) with python
Python Exercise for Beginners # 2 [for Statement / While Statement]
Getting Started with Python for PHPer-Classes
Python #index for super beginners, slices
<For beginners> python library <For machine learning>
AWS Layer Creation Script for python
Python #len function for super beginners
Beginners use Python for web scraping (1)
Run unittests in Python (for beginners)
Beginners use Python for web scraping (4) ―― 1
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners
Getting Started with Python for PHPer-Functions
[Pandas] I tried to analyze sales data with Python [For beginners]
Easy keyword extraction with TermExtract for Python
WEB scraping with Python (for personal notes)
[Python] Minutes of study meeting for beginners (7/15)
Manually ssh registration for coreserver with python
Use DeepL with python (for dissertation translation)
Memo to ask for KPI with python
Amplify images for machine learning with python
[Episode 2] Beginners tried Numeron AI with python
[Episode 3] Beginners tried Numeron AI with python
Tips for dealing with binaries in Python
Let's put together Python for super beginners
[Shakyo] Encounter with Python for machine learning
Process multiple lists with for in Python
[Episode 0] Beginners tried Numeron AI with python
Getting Started with Python for PHPer-Super Basics
[Episode 1] Beginners tried Numeron AI with python
Debug for mysql connection with python mysql.connector
Excel table creation with Python [Progress management table]
How Python beginners get started with Python with Progete
Atcoder standard input set for beginners (python)
Preparation for scraping with python [Chocolate flavor]
A textbook for beginners made by Python beginners
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
Beginners use Python for web scraping (4) -3 GCE VM instance creation and scraping on VM
Easy-to-understand explanation of Python Web application (Django) even for beginners (2) [Project creation]
Rock-paper-scissors with Python Let's run on a Windows local server for beginners
Error due to UnicodeDecodeError when reading CSV file with Python [For beginners]
Notes for Python beginners with experience in other languages 12 (+1) items by function
2016-10-30 else for Python3> for: