(* Since the edit request was merged, the code has changed significantly. There is no change in the function.)
Quickly create an API that allows you to easily read and write JSON from the client.
--Use Python2.7 / Flask. --Generate / read / write JSON file instead of DB.
--Python environment construction. --Detailed code explanation.
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.
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
});
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
});
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
});
First of all, I made it as small as possible.
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)
$ python api.py
The web server will start, so access and use http://127.0.0.1:5000
.
For the time being, I wrote a test in requests and put it on Github.
https://github.com/naoiwata/simple-flask-api