'how to retrive a value from request and do processing and post it to another link flask

I am new to using flask, what I need to know is to listen to a request and do some processing on one field of this request and return some extra value and post it along with this field to another link, what I can think of rn is something like this to retrieve the age should I do something like this? :

from flask import Flask, jsonify, request

app = Flask(__name__)
#sample of json: json ={'phone_number':"+345xxxxxxxx","name":"sss","gender":"female","age":23}


@app.route('link', methods=['GET','POST'])
def get_request():
    data = request.get_json
    age= data['age']
    return age


if __name__ == "main":
    
    app.run(port= 2000,debug=True)

as I understand that the previous code, retrieves the age, but what if I want to define a new function that does some calculations to the age and then post it to another uri? I am quite lost on this. any help would be appreciated thanks



Solution 1:[1]

Be careful because there are some errors in your piece of code that make it impossible for the application to run.

It is not very clear to me what you have to do, once you have obtained the age from the json, you perform a series of calculations and then you can do with it what you want, in this case I will pull it as an answer to the call. What do you mean with "post it to another uri", if the value you calculate must be used by the client in the future then it's fine as I posted, if instead the flask application must use it, you have to save the data for when you need it.

from flask import Flask, jsonify, make_response, request

app = Flask(__name__)
# sample of json: json ={'phone_number':"+345xxxxxxxx","name":"sss","gender":"female","age":23}


def foo(age: int) -> int:
    return age + 1


@app.route('/link', methods=['GET', 'POST'])
def get_request():
    data = request.get_json()
    age = foo(int(data['age']))
    return make_response(
                jsonify(
                    {"age": age}
                ),
                200,
            )


if __name__ == "__main__":
    app.run(port=2000, debug=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matteo Pasini