Python: Put request to rest api sends Bad request 400 error

3.6k Views Asked by At

I am sending a Put request to Rest Api to update user information based on username, and it gives following error

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

API brief as follow

/api/users/username GET, PUT    Token

I create my request as follow,

headers = {'Content-Type': 'application/json',
'Token': token}

datap = [{'firstname': 'aaa1',
'lastname': 'aaa1',
'phone': '222222'}]

r = requests.put('http://127.0.0.1:8080/api/users/user1a', data=datap, headers=headers)
print(r.text)

If further information needed I can provide that too ok here is snippit of the code to the rest api

@bp.route('/users/<username>', methods=(['GET', 'PUT']))
@token_required
def username(username):
    if request.method == 'GET':
        return get_specific_user(username)
    if request.method == 'PUT':
        return put_specific_user(username, request)

def put_specific_user(username, request):
    allowed_fields = ('firstname', 'lastname', 'phone')
    if not request.is_json:
        return jsonify({'status': 'FAILURE',
                        'message': 'Bad Request'}), 400

After enclosing json into [] now I am getting following error, so its not bad request anymore

File "C:\Python27\lib\site-packages\requests\api.py", line 131, in put
    return request('put', url, data=data, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Python27\lib\site-packages\requests\models.py", line 316, in prepare
    self.prepare_body(data, files, json)
  File "C:\Python27\lib\site-packages\requests\models.py", line 507, in prepare_body
    body = self._encode_params(data)
  File "C:\Python27\lib\site-packages\requests\models.py", line 97, in _encode_params
    for k, vs in to_key_val_list(data):
ValueError: too many values to unpack
1

There are 1 best solutions below

0
On

changed following

requests.put('http://127.0.0.1:8080/api/users/user1a', data=datap, headers=headers)

to

requests.put('http://127.0.0.1:8080/api/users/user1a', data=json.dumps(datap), headers=headers)

PS: I wouldnt know why someone would give me -1 for this question can some mod please look into it. so that I dont do it again.