Home > Mobile >  Combining sum of two numbers from REST API (json)
Combining sum of two numbers from REST API (json)

Time:06-16

Blessings,

I have a REST API flask application which returns a JSON with the following through a POST request

{
    "you sent": [
        {
            "number": "5"
        },
        {
            "number": "10"
        }
    ]
}

My goal is to combine both sum of the numbers.. this might be quite simple but im at a loss :)

flask app

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {'about': 'Hello World'}

    def post(self):
        some_json = request.get_json()
        return {'you sent': some_json}, 201


api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

main.py

import requests

url = 'http://127.0.0.1:5000/'
myobj = {'number': '5'}
mysecobj = {'number': '10'}

x = requests.post(url, json=(myobj, mysecobj))

print(x.text)

CodePudding user response:

Firstly, you need to send your numbers like float or int:

myobj = {'number': 5}
mysecobj = {'number': 10}

Secondly, get your numbers from request, sum it and return back as result:

def post(self):
    some_json = request.get_json()
    number1 = some_json[0]['number']
    number2 = some_json[1]['number']
    _sum = number1   number2
    return {'result': _sum}, 201

CodePudding user response:

This code is ugly but functional. I suggest you find a nicer format of sending data in future but this works given the objects you have.

dic = {
    "you sent": [
        {
            "number": "5"
        },
        {
            "number": "10"
        }
    ]
}

sum = int(dic["you sent"][0]["number"])   int(dic["you sent"][1]["number"])
print(sum)
  • Related