Search code examples
pythonapioauthpython-requestsyahoo-api

Retrieve access token for Yahoo API using OAuth 2.0 and Python requests


I am trying to retrieve the access token for the Yahoo API, using the explicit grant flow as described in this document: https://developer.yahoo.com/oauth2/guide/flows_authcode

Everything is fine until Step 4: Exchange authorization code for Access Token

I wrote the following python script to retrieve the code:

import urllib2
import requests
import json



url = 'https://api.login.yahoo.com/oauth2/get_token'
body = "grant_type=authorization_code&redirect_uri=oob&code=************"
headers = {
'Authorization': 'Basic **************', 
'Content-Type': 'application/json'
}

r = requests.post(url, data=body, headers=headers)
print r

Note: I replaced sensitive data with "****"

Now, when I execute the script, I only get the "401" error message.

I am 100% sure that the login credentials are fine, so it seems to be related to the way I make the request. It's also the first time that I am using "requests" in python.

Would be great, if you could give me some feedback on the code, and if I am passing the header and body information correctly. I am especially unsure about the passing of the body. The documentation only states the following:

Sample Request Body: grant_type=authorization_code&redirect_uri=https%3A%2F%2Fwww.example.com&code=abcdef


Solution

  • Change your body variable to a dict, i.e.,

    body = {
        'grant_type': 'authorization_code',
        'redirect_uri': 'oob',
        'code': '************',
    }
    

    No other changes are needed. Hope it helps.