Search code examples
pythoncurlpycurl

How to translate this Curl command into a Pycurl call?


I am running the following curl command that I run from the Unix command line to do Google OAuth and it works perfectly fine. I get a response containing an access token.

curl \
--request POST \
--header "Cache-Control: no-cache" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data 'code=my-first-magic-code&client_id=my-magic-client-id&grant_type=authorization_code&client_secret=my-magic-client-secret&redirect_uri=http://www.my-magic-website.com/google-login-callback' \
"https://accounts.google.com/o/oauth2/token"

Response (200):

{
  "access_token": "ya29.Glwb-blah-blah-blah-pjKiA",
  "expires_in": 3575,
  "scope": "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
  "token_type": "Bearer",
  "id_token": "eyJhb-blah-blah-blah-Xjz4g"
}

How can I write the equivalent command using pyCurl? Below is what I wrote:

#!/usr/bin/env python

import pycurl
from StringIO import StringIO
import httplib
import json

response_buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://accounts.google.com/o/oauth2/token')
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded',
                             'Cache-Control: no-cache'])
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, json.dumps({
    'code': raw_input('Enter the new Auth Code you got from the web here: '),
    'client_id': 'my-magic-client-id',
    'client_secret': 'my-magic-client-secret',
    'grant_type': 'authorization_code',
    'redirect_uri': 'http://www.my-magic-website.com/google-login-callback'
}))

c.setopt(c.WRITEDATA, response_buffer)
c.perform()
if c.getinfo(pycurl.HTTP_CODE) == httplib.OK:
    print 'Worked! {}'.format(json.loads(response_buffer.getvalue()))
else:
    print 'Failed! {}'.format(json.loads(response_buffer.getvalue()))

However when I run this program, it fails as follows:

Enter the new Auth Code you got from the web here: my-second-magic-code
Failed! {u'error_description': u'Invalid grant_type: ', u'error': u'unsupported_grant_type'}

Solution

  • How about this modification?

    From:

    c.setopt(pycurl.POSTFIELDS, json.dumps({
    

    To:

    c.setopt(pycurl.POSTFIELDS, urllib.urlencode({
    

    Note :

    • In this case, also please add import urllib.
    • Before you run this script, please retrieve the code again and run the script.