Rajeev
Rajeev

Reputation: 46899

POST data with urllib2 gives 400

In the following code, when the following data(template_data) is passed in postman app on chrome then there is a response but the same data when posted with urllib2 gives an error, The only difference i notice is the required field i.e, false should not be given in quotes even in postman script else there is no response but the same fails in urllib2

If 'false' is given quotes in template_data even then the result is 400

Edit: In postman false should not be given in quotes if gives gives an error, so not sure how to send this paramater

 import urllib
 import urllib2

 def get_url_data(url, request_method, content_type, data=None, 
                 headers={}):
    method = request_method
    handler = urllib2.HTTPHandler(debuglevel=1)
    opener = urllib2.build_opener(handler)
    if data is not None:
        data = urllib.urlencode(data)
    request = urllib2.Request(url, data=data,headers=headers)
    request.add_header("Content-Type", content_type)
    request.get_method = lambda: method
    try:
        connection = opener.open(request)
    except urllib2.HTTPError,e:
        connection = e
    print connection.code
    if connection.code == 200:
        resp = connection.read()
        return resp
    return None

form_template_url="https://example.com"
auth='sometokenid'
template_header_param = {'Authorization':auth}
template_data = {
  "templateName": "somename", 
  "category": "Handbook", 
  "formTemplateDef": [{
    "id": "0",
    "component": "textInput", 
    "editable": "true",
    "index": "0", 
    "label": "Handbook",
    "description": "", 
    "placeholder": "TextInput",
    "options": [], 
    "required": 'false'
   }]
}
template_response = get_url_data(form_template_url,
  'POST', 'application/json',
   template_data, template_header_param)

Upvotes: 0

Views: 230

Answers (1)

eshwar m
eshwar m

Reputation: 184

Remove

data = urllib.urlencode(data) 

and use

urllib2.urlopen(req, json.dumps(data))

This should work.

Upvotes: 1

Related Questions