Sending a JSON POST using urllib2 results in HTTP 422
Question: i have been having a problem sending a JSON request towards an API. I've added
application type headers though the API still responds with HTTP 422. The JSON
file data is valid, checked via jsonlint.

    
    
    post_config = urllib2.Request(config_url)
    post_config.add_header('AUTHORIZATION', 'Token token=hash')
    post_config.add_header('Content-Type', 'application/json')
    post_data = json.dumps(post_data)
    print post_data
    >>{"type": "numeric", "instance_id": "e0140", "name": "name0140", "uid": "970ebb1b2549b4dd5254", "instance_type": "Recommended", "power": "high"}
    send = urllib2.urlopen(post_config, post_data)
    

Results in:

    
    
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
    urllib2.HTTPError: HTTP Error 422: Unprocessable Entity
    


Answer: Try using the requests module instead and see if you're still getting the same
response.

# Snippet example on how to POST the payload to a REST endpoint

    
    
    import requests
    import json
    
    url = 'http://example.com/endpoint'
    headers = {'Content-type': 'application/json'}
    data = json.dumps(post_data)
    print(data)
    r = requests.post(url, data=json.dumps(payload),headers=headers)
    print(r.status_code)
    

