How to resolve TypeError: 'Request' object is not callable Error in Flask?

Question:

I am trying to learn Flask. and here I am facing an issue.

I have created a route ( /register ) in my Flask app.
and I am trying to trigger this using Postman.

But I am getting this Error:

TypeError: 'ImmutableMultiDict' object is not callable

Here is my code for /register route.

@app.route('/register', methods=['POST'])
def register():
    if request.method == 'POST':
        fname = request.form(["fname"])
        mname = request.form(["mname"])
        lname = request.form(["lname"])
        gender = request.form(["gender"])
        age = request.form(["age"])
        email = request.form(["email"])
        password = request.form(["password"])

        new_member = User(fname, mname, lname, gender, age, email, password)

        try:
            db.session.add(new_member)
            db.session.commit()
            return redirect('/')
        except:
            return 'Error: Error found'

Here is request body that I am sending from Postman.

{
    "fname":"ashutosh",
    "mname":"kumar",
    "lname":"yadav",
    "gender":"m",
    "age":25,
    "email":"[email protected]",
    "password": "PassWord@123"
}

But I am getting this Error: TypeError: 'ImmutableMultiDict' object is not callable

In case if it is needed, here is curl request.

curl --location --request POST 'http://127.0.0.1:5000/register' 
--header 'Content-Type: application/json' 
--data-raw '{
    "fname":"ashutosh",
    "mname":"kumar",
    "lname":"yadav",
    "gender":"m",
    "age":25,
    "email":"[email protected]",
    "password": "PassWord@123"
}'

A similar problem I found on SOF

But I am not able to figure out what issue is there in my code.

Kindly help me guys.

Asked By: Ashutosh Yadav

||

Answers:

request.form works only if you POST data with the application/x-www-form-urlencoded or multipart/form-data. Since your POST data is JSON , make sure you are using request.json or change your content-type in curl to application/x-www-form-urlencoded

content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
    body = request.json
    fname = body["fname"]
    mname = body["mname"]
    lname = body["lname"]
    gender = body["gender"]
    age = body["age"]
    email = body["email"]
    password = body["password"]
Answered By: Ashish M J
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.