Search code examples
pythonparsingsqlalchemyflask-restful

flask restful and sqlalchemy error: "uname": "Missing required parameter in the JSON body"


 parser = reqparse.RequestParser()
 parser.add_argument('uname', type = unicode, required = True, location= 'json')
 parser.add_argument('pword', type = unicode, required = True, location= 'json')
 parser.add_argument('fname', type = unicode, required = True, location= 'json')
 parser.add_argument('lname', type = unicode, required = True, location= 'json')
 parser.add_argument('gender', type = unicode, required = True, location= 'json')
 parser.add_argument('email_id', type = unicode, required = True, location= 'json')

 session= Session()
 class store_user(Resource):
    def post(self):
        #args=request.get_json(force = True)
        args = parser.parse_args()
        unq_id = str(uuid.uuid4()) 

        user_data = {'uid' : unq_id, 'username' : args['uname'], 'password' : args['pword'], 'f_name' : args['fname'],              
                        'l_name' : args['lname'], 'sex' : args['gender'], 'email_id' : args['email_id']}
        auser = user(uid = user_data['uid'], username = user_data['username'], password = user_data['password'], f_name =
                    user_data['f_name'], l_name = user_data['l_name'], sex =
                    user_data['sex'], email_id = user_data['email_id'])
        session.add(auser)
        session.commit()    


        #return user_data
        #return jsonify(auser)

 api.add_resource(store_user, '/user', endpoint='user')

I'm getting an error while adding new data to the database. user is a class that is mapped to user_info table and a user is the object of the user class. I'm facing a problem while parsing the request data but I'm not able to solve it. Below is the output on the terminal using curl command:

command:

curl http://127.0.0.1:5000/user -d "uname= man, pword= uuoiuu, fname= manish, lname= kumar, gender= male, emailid= mkcomp12@gmail.com" -X POST -v

output:

> * Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> POST /user HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:5000
> Accept: */*
> Content-Length: 99
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 99 out of 99 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 400 BAD REQUEST
< Content-Type: application/json
< Content-Length: 90
< Server: Werkzeug/0.9.4 Python/2.7.6
< Date: Thu, 28 Jan 2016 07:31:56 GMT
< 
{
    "message": {
        "uname": "Missing required parameter in the JSON body"
    }
}

Solution

  • I think there are two issues with your curl command:

    1. You need to hand over -H "Content-Type: application/json" to show that you will send json data (have a look at this answer)

    2. You have to hand over your data as json data:

      '{"uname":"man","pword":"uuoiuu"}'