[JAVA] Create a simple API just to input and output JSON files ~ Python / Flask edition ~

(* Since the edit request was merged, the code has changed significantly. There is no change in the function.)

Purpose

Quickly create an API that allows you to easily read and write JSON from the client.

What to do in this article

--Use Python2.7 / Flask. --Generate / read / write JSON file instead of DB.

What not to do in this article

--Python environment construction. --Detailed code explanation.

background

I want to change the UI depending on the state of the content, the state of the user, etc. I wanted a JSON that returns the state so that I can add / change the screen state and parameters while making a client (around the Web), so I made a simple one. It's as simple as running it in your local environment. (It is assumed that a dedicated application server will be used in the production environment.)

API

It is an API that treats JSON like KVS, with the JSON file name as key and the data to be retrieved (JSON) as value. Locally use Flask to launch http://127.0.0.1:5000 and interact with it.

Get values (JSON) by specifying key

Used to get <key> .json.

$ curl http://127.0.0.1:5000/api/<key> -X GET
$.ajax({
  type: 'GET'
  url:'http://127.0.0.1:5000/api/<key>'
}).done(function(res){
  //Processing after GET
});

Add or update values (JSON) with key

It is used to register (or overwrite), for example, {" status ": 0} in <key> .json.

$ curl http://127.0.0.1:5000/api/<key> -X POST\
  --data '{"status": 0}' -H "Content-type: application/json"
$.ajax({
  type: 'POST',
  url:'http://127.0.0.1:5000/api/<key>',
  data: '{"status": 0}',
  headers: {
    'Content-Type': 'application/json'
  }
}).done(function(res){
  //Processing after POST
});

Delete the parameter (json_key) in the values (JSON) associated with the key

If <key> .json contains, for example,{"<json_key>": <arbitrary value>}, remove the<json_key>element from <key> .json.

$ curl http://127.0.0.1:5000/api/<key>/<json_key> -X DELETE
$.ajax({
  type: 'DELETE',
  url:'http://127.0.0.1:5000/api/<key>/<json_key>'
}).done(function(res){
  //Processing after DELETE
});

wrote

First of all, I made it as small as possible.

API implementation part

api.py


# -*- coding: utf-8 -*-

import json

from flask import Flask, request, jsonify


app = Flask(__name__)


"""Routing:Calls the process according to the request URI and method and returns the result."""
@app.route('/', methods=['GET'])
def hello():
    return 'hello:)'


@app.route('/api/<key>', methods=['GET'])
def get(key):
    model = get_model(key)
    if model is None:
        return "NOT FOUND"
    else:
        return jsonify(model)


@app.route('/api/<key>', methods=['POST'])
def post(key):
    result = set_property(key, json.loads(request.data))
    return jsonify(result)


@app.route('/api/<key>/<property_name>', methods=['DELETE'])
def delete(key, property_name):
    result = delete_property(key, property_name)
    if result is None:
        return "NOT FOUND"
    else:
        return jsonify(result)


"""Manipulation on the model"""
def get_model(key):
    return read_model(key)


def set_property(key, properties):
    data = read_model(key)
    if data is None:
        data = {}
    data.update(properties)
    result = write_model(key, data)
    return result


def delete_property(key, property_name):
    data = read_model(key)
    if data is None:
        return None
    if property_name not in data:
        return None
    del data[property_name]
    result = write_model(key, data)
    return result


"""Persistence layer access"""
def read_model(key):
    file_name = key + '.json'
    try:
        with open(file_name, 'r') as f:
            return json.load(f)
    except IOError as e:
        print e
        return None


def write_model(key, data):
    file_name = key + '.json'
    try:
        with open(file_name, 'w') as f:
            json.dump(data, f, sort_keys=True, indent=4)
            return data
    except IOError as e:
        print e
        return None


if __name__ == '__main__':
    app.run(debug=True)

How to use

$ python api.py

The web server will start, so access and use http://127.0.0.1:5000.

Refactored and put on Github

For the time being, I wrote a test in requests and put it on Github.

https://github.com/naoiwata/simple-flask-api

Recommended Posts

Create a simple API just to input and output JSON files ~ Python / Flask edition ~
How to create a JSON file in Python
python input and output
[Python] How to split and modularize files (simple, example)
Python script to create a JSON file from a CSV file
[Python Kivy] How to create a simple pop up window
Just try to receive a webhook in ngrok and python
Rubyist tried to make a simple API with Python + bottle + MySQL
[Python / Django] Create a web API that responds in JSON format
Create a simple scheduled batch using Docker's Python Image and parse-crontab
[Python] Conversation using OpenJTalk and Talk API (up to voice output)
Export and output files in Python
Python logging and dump to json
5 Ways to Create a Python Chatbot
Create a simple Python development environment with VS Code and Docker
[Python] Create API to send Gmail
How to input a character string in Python and output it as it is or in the opposite direction.
Challenge to create time axis list report with Toggl API and Python
[Python] Create a linebot to write a name and age on an image
[Python / Tkinter] Search for Pandas DataFrame → Create a simple search form to display
I tried to create a sample to access Salesforce using Python and Bottle
I want to make a web application using React and Python flask
Data input / output in Python (CSV, JSON)
Create a simple GUI app in Python
Reading and writing JSON files with Python
Create a simple web app with flask
Read and write JSON files in Python
[Python] Quickly create an API with Flask
[Python] Add comments to standard input files
Create a simple app that incorporates the Fetch API of Ajax requests in Flask and explain it quickly
Create an API to convert PDF files to TIF images with FastAPI and Docker
I tried to create a class that can easily serialize Json in Python
Create a simple reception system with the Python serverless framework Chalice and Twilio
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
[ES Lab] I tried to develop a WEB application with Python and Flask ②
[Python] Concatenate a List containing numbers and write it to an output file.
Create a web app that converts PDF to text using Flask and PyPDF2
Create a filter to get an Access Token in the Graph API (Flask)
I tried to make a simple image recognition API with Fast API and Tensorflow
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
[Python] List Comprehension Various ways to create a list
How to create a Python virtual environment (venv)
Just add the python array to the json data
I want to create a window in Python
How to generate a Python object from JSON
Create a web map using Python and GDAL
Output python log to both console and file
Steps to create a Twitter bot with python
Create a simple momentum investment model in Python
How to create a Kivy 1-line input box
Batch conversion of Excel files to JSON [Python]
Create a Mac app using py2app and Python3! !!
How to create a Rest Api in Django
Create a discord bot that notifies unilaterally with python (use only requests and json)
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
[Mac] A super-easy way to execute system commands in Python and output the results
Parse a JSON string written to a file in Python
Procedure to load MNIST with python and output to png
[LINE Messaging API] Create a rich menu in Python