93 lines
3.1 KiB
Python
93 lines
3.1 KiB
Python
from flask import Flask, request, jsonify
|
|
|
|
data_store = {}
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route("/counters", methods=['GET', 'POST'])
|
|
def handle_counters_endpoint():
|
|
if request.method == 'GET':
|
|
response_dict = {
|
|
'all_counters': data_store
|
|
}
|
|
return jsonify(response_dict), 200
|
|
elif request.method == 'POST':
|
|
if request.content_type == 'application/json':
|
|
body = request.get_json()
|
|
|
|
if not "new_counter_name" in body.keys() or not "new_counter_starting_value" in body.keys():
|
|
error_response = {
|
|
'status': 'ERROR',
|
|
'reason': 'Body for posting to /counters endpoint must contain both new_counter_name and new_counter_starting_value',
|
|
'input_body': body
|
|
}
|
|
return jsonify(error_response), 400
|
|
|
|
data_store[request.get_json()['new_counter_name']] = request.get_json()['new_counter_starting_value']
|
|
return jsonify({'status': 'OK'}), 200
|
|
else:
|
|
error_response = {
|
|
'status': 'ERROR',
|
|
'reason': 'Content Type for endpoint /counters must be application/json'
|
|
}
|
|
return jsonify(error_response), 400
|
|
|
|
@app.route("/counters/<counter_name>", methods=['GET'])
|
|
def handle_counters_subcounter_endpoint(counter_name):
|
|
if not counter_name in data_store.keys():
|
|
error_response = {
|
|
'status': 'ERROR',
|
|
'reason': 'Counter name {counter} does not exist'.format(counter=counter_name)
|
|
}
|
|
return jsonify(error_response), 404
|
|
|
|
data_response = {
|
|
'counter_name': counter_name,
|
|
'counter_value': data_store[counter_name]
|
|
}
|
|
|
|
return jsonify(data_response), 200
|
|
|
|
@app.route("/counters/<counter_name>/increment", methods=['POST'])
|
|
def handle_counters_subcounter_increment(counter_name):
|
|
if not counter_name in data_store.keys():
|
|
error_response = {
|
|
'status': 'ERROR',
|
|
'reason': 'Counter name {counter} does not exist'.format(counter=counter_name)
|
|
}
|
|
return jsonify(error_response), 404
|
|
|
|
data_response = {
|
|
'counter_name': counter_name,
|
|
'old_value': data_store[counter_name],
|
|
'new_value': data_store[counter_name] + 1
|
|
}
|
|
|
|
data_store[counter_name] = data_store[counter_name] + 1
|
|
|
|
return jsonify(data_response), 200
|
|
|
|
@app.route("/counters/<counter_name>/decrement", methods=['POST'])
|
|
def handle_counters_subcounter_decrement(counter_name):
|
|
if not counter_name in data_store.keys():
|
|
error_response = {
|
|
'status': 'ERROR',
|
|
'reason': 'Counter name {counter} does not exist'.format(counter=counter_name)
|
|
}
|
|
return jsonify(error_response), 404
|
|
|
|
data_response = {
|
|
'counter_name': counter_name,
|
|
'old_value': data_store[counter_name],
|
|
'new_value': data_store[counter_name] - 1
|
|
}
|
|
|
|
data_store[counter_name] = data_store[counter_name] - 1
|
|
|
|
return jsonify(data_response), 200
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True)
|
|
|