urllib2.HTTPError: HTTP Error 400: Bad Request - Python


I'm trying to POST using urllib and urllib2 but it keeps giving me this error

Traceback (most recent call last): File "/Users/BaDRaN/Desktop/untitled text.py", line 39, in <module> response = urllib2.urlopen(request) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen return _opener.open(url, data, timeout) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open response = meth(req, response) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response 'http', request, response, code, msg, hdrs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error return self._call_chain(*args) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain result = func(*args) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 400: Bad Request

and here's my code

body = {'where' : {'deviceType' : 'ios'}, 'data' : {'alert' : 'vvv'}} headers = { 'X-Parse-Application-Id' : 'someID', 'X-Parse-REST-API-Key' : 'someKey', 'Content-Type' : 'application/json' } data = urllib.urlencode(body) request = urllib2.Request('https://api.parse.com/1/push', data, headers) response = urllib2.urlopen(request) call = response.read()

Anyone could help me here ?


My psychic powers suggest you want to send body as a string of json, not as a dictionary that's converted to a string.

body = '{"where" : {"deviceType" : "ios"}, "data" : {"alert" : "vvv"}}'

Notice the use of double-quotes for the json elements.


I suspect your payload is not correctly encoded. Nowhere they say "urlencoded". Try using their own example instead. <a href="https://parse.com/docs/rest#push" rel="nofollow">https://parse.com/docs/rest#push</a> urrlib2 is a rather primitive library - using e.g. requests would be more convenient.


It depends whether the json data is in correct format or not, or the issue is in the header content. Hence the urllib2.HTTPError: HTTP Error 400: Bad Request usually occurs.

A small piece of code below with the basic64 authentication with the headers and the json data for the PUT/POST methods:

import urllib2 import base64 import json url = 'Your_URL' auth = 'Basic ' + base64.encodestring('%s:%s' % ('username','password'))[:-1] content_header = {'Authorization': auth, 'Content-Type':'application/json', 'Accept':'application/json'} json_data = YOUR_DATA request = urllib2.Request(url=url, data=json.dumps(json_data), headers=content_header) request.get_method = lambda: 'PUT' #If you will not provide this, then it will be POST response = urllib2.urlopen(request)


  • urllib2.HTTPError: HTTP Error 400: Bad Request - Python
  • How can I retrieve files with User-Agent headers in Python 3?
  • NameError, global not defined when using try,except
  • python urllib2 can open localhost but not
  • Breeze webapi controller 'cannot support querying' over DbSet error
  • NodeJs http status exception handling
  • Cherrypy - reciving JSON data 404, 'Missing parameters'
  • Avoid inheriting generated class attributes using metaclass
  • How do I stop a clicked combo box from clearing its value?
  • JScrollPane problem
  • How do I catch the “Error during processing: buffer error” in Ruby when getting a web page?
  • Proper way to get file size in C
  • Functional Programming in Swit to distribute array elements to correct “buckets”
  • SWIG ImportError: undefined symbol: _Py_RefTotal
  • Replace value in unordered list (html) + JQuery
  • Custom Nav Title offset ios 11
  • How to synchronize two scrollview in Android?
  • Element.tagName for python not working
  • Odoo 10 - Overriding unlink method
  • How to Cache Real-time Data?
  • Functions in global context
  • Spring Data JPA custom method causing PropertyReferenceException
  • Update CALayer sublayers immediately
  • Possible to stop flickering java tooltip in heavyweight mode?
  • php design question - will a Helper help here?
  • AngularJs get employee from factory
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Checking variable from a different class in C#