Simple Python API

neelam singhal
Jul 28, 2022


Creating a simple python API using Flask

Input: {“operation”: “sum”, “operands”: [2,2,4]}

“operation” can be average, sum , median, mode

Output: {“answer”: 8}

from flask import Flask, jsonify, request
from statistics import mean, median, mode
app = Flask(__name__)@app.route("/calculate", methods=['POST'])def calculate():
data = request.get_json()
function = data['operation'].lower()
list_vals = data['operands']
if function == 'sum':
return jsonify({"answer":sum(list_vals)})
elif ((function == 'average') | (function == 'avg') | (function == 'mean')):
return jsonify({"answer":mean(list_vals)})
elif (function == 'median'):
return jsonify({"answer":median(list_vals)})
elif (function == 'mode'):
return jsonify({"answer":mode(list_vals)})

return "Operation not available"
if __name__ == "__main__":

Testing it in Postman:

Ensure that you have selected “Content-type” as “application/json”, else you will keep getting the following error: “Content-Type was not ‘application/json’”

The input request and output are displayed in Postman screenshot below.



neelam singhal


See more recommendations