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.



Q1: Write a query to reverse a number in python

n= 3648
m = 0
while n!=0:
m = m*10 + n%10
n = n//10

Q2: Check if two strings are palindrome

s1 = "madam"if(s1 == s1[::-1]):
print ("This is a palindrome")
print ("not palindrome")

Q3: Email Slicer

Option 1:

email = input("enter your email: " ).strip()username = email.split('@')[0]
domain_name = email.split('@')[1]
print("Username: " ,username, "\nDomain_name: ",domain_name)

Option 2:

email = input("enter your email: " ).strip()username = email[:email.index('@')]
domain_name = email[email.index('@')+1:]
print("Username: " ,username, "\nDomain_name: ",domain_name)