user3626708
user3626708

Reputation: 767

python making POST request with JSON data

I'm trying to mimic a curl request I'm doing using python the call is. Note that

The curl command I used is

curl -k --dump-header - -H "Content-Type: application/json" -X POST --data '{"environment_name": "foo"}' https://localhost/api/v1/environment/

and the response from the server is successful

HTTP/1.1 201 CREATED
Date: Tue, 17 Jun 2014 00:59:59 GMT
Server: Server
Vary: Accept-Language,Cookie,User-Agent
Content-Language: en-us
Location: https://localhost/api/v1/environment/None/
Status: 201 CREATED
Content-Length: 0
Cneonction: close
Content-Type: text/html; charset=utf-8

However when I try to do a post request in python with 'requests' my script is

import json
data = {'enviornment_name' : 'foo'}

headers = {'Content-type' : 'application/json'}
response = requests.post("https://localhost/api/v1/environment", headers=headers, data=data, verify=False)

When running the script I get back a huge stack trace but the part in red is

E                   DecodeError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing: incorrect data check',))

I'm not sure why I can't my script to work via python

Upvotes: 2

Views: 3735

Answers (2)

user3626708
user3626708

Reputation: 767

@Fabricator I need the verify=False however I noticed the one thing in my code that was an issue for the server I was using I needed the trailing '/' at the end of the URI. In addition I also needed the json.dumps(data) not json.dump(data) in case others are looking. Thanks for the help

Upvotes: 1

Ian Stapleton Cordasco
Ian Stapleton Cordasco

Reputation: 28707

Your server is claiming to return gzip'd content which it is not. The response is returning Content-Encoding: gzip in the headers. This could be because in requests, by default, it sends Accept-Encoding: gzip, compress. You should try setting "Accept-Encoding" to None in your headers dictionary in addition to @Fabricator's suggestion in the comments.

Your headers dictionary will look like:

headers = {'Content-Type': 'application/json', 'Accept-Encoding': None}

And your call to requests will look like

requests.post(url, headers=headers, data=json.dumps(data), verify=False)

Upvotes: 5

Related Questions