Reputation: 86
I have to make this endpoints por my api or service: addition just returns the addition of a
and b
and the same thing with de division. The last route has to return in a json format with the json which was send by url.
addition/{a}/{b}
, division/{a}/{b}
, and
url/json
How can I get multiple parameters from a URL using that way. I've already know this way ->
@app.route('/api/addition/', methods=['GET'])
def add():
a = request.args.get('a')
b = request.args.get('b')
(... some stuff ...)
is any other way to do it?
Thanks for your help, sorry English is nor my first language, maybe I made some grammar mistake. I apologize about that. viviramji.
Upvotes: 1
Views: 1916
Reputation: 71451
You can create a route that accepts the two values, along with the desired operation type:
import operator
@app.route('/api/<operation>/<a>/<b>', methods=['GET'])
def perform_operation(operation, a, b):
_ops = {'addition':operator.add, 'subtraction':operator.sub, 'multiplication':operator.mul, 'division':operator.truediv}
if operation not in _ops:
return flask.jsonify({'success':False})
return flask.jsonify({'success':True, 'result':_ops[operation](float(a), float(b))})
Upvotes: 0
Reputation: 1639
This might help.
POST
request Flask
API.You can send custom data and operation of any type you want. you can test the following code with postman
. Make sure the raw data you send from postman
is application/json
type.
from flask import Flask, url_for, json,request, Response, jsonify
app = Flask(__name__)
@app.route('/api/addition/', methods=['POST'])
def add():
requestJson = request.json
print(requestJson)
val1 = requestJson['val1']
val2 = requestJson['val2']
operation = requestJson['operation']
respDict = {"Message":None,"Value":None}
if operation.lower() == "addition":
val = val1 + val2
respDict['Message']="addition"
if operation.lower() == "division":
respDict['Message']="division"
val = val1/val2
respDict['Value']=val
resp = Response(json.dumps(respDict), status = 200)
return resp
import sys
if __name__ == '__main__':
if(len(sys.argv) > 1):
portString = sys.argv[1]
else:
portString = "5200"
app.run(
host = "0.0.0.0",
port=int(portString),
debug=True,
threaded = True)
Here is the requestJson
{
"val1":3,
"val2":2,
"operation":"addition"
}
Disclaimer: This not might exactly answer your question but solves your problem.
Upvotes: 0