jorrebor
jorrebor

Reputation: 2232

How to make a post request with REQUESTS package for Python?

I am trying to use the toggl api.

I use Requests instead of Urllib2 for doing my GETs en POSTS. But i am stuck.

payload = {
    "project":{
        "name":"Another Project",
        "billable":False,
        "workspace":{
            "Name":"jorrebor's workspace",
            "id":213272
        },
        "automatically_calculate_estimated_workhours":False
    }
}

url = "https://www.toggl.com/api/v6/projects.json"
r = requests.post(url, data=json.dumps(payload), auth=HTTPBasicAuth('[email protected]', 'mypassword'))

Authentication seems to be fine, but the payload format probably isn't.

a curl command with the same parameters:

curl -v -u heremytoken:api_token -H "Content-type: application/json" -d "{\"project\":{\"billable\":true,\"workspace\":{\"id\":213272},\"name\":\"Another project\",\"automatically_calculate_estimated_workhours\":false}}" -X POST https://www.toggl.com/api/v6/projects.json

does work fine.

What wrong with my payload? The response is get is: ["Name can't be blank","Workspace can't be blank"]

which leads me to conclude that the authentication works but toggl cannot read my json object.

Upvotes: 2

Views: 2208

Answers (1)

TankorSmash
TankorSmash

Reputation: 12747

Seems like you should try setting the header to a JSON application, rather than the default format, and send a JSON object instead of the Python dict. Check it out here:

payload = {"project":{"name":"Another Project",
                     "billable":False,
                     "workspace":{"Name":"jorrebor's workspace",
                                  "id":213272},
                     "automatically_calculate_estimated_workhours":False
                      }   } 

parameters_json = json.dumps(payload)
headers = {'Content-Type': 'application/json')
r = client.post(url, data=parameters_json, headers=headers)

which should allow the site to read the json object just fine.

Upvotes: 2

Related Questions