且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用OAuth 2.0和Python请求检索雅虎API访问令牌

更新时间:2023-02-16 08:04:11

你的身体变量更改为一个字典,即,

  =身体{
    grant_type':'authorization_ code',
    REDIRECT_URI':'OOB',
    code':'************',
}

不需要进行其他的变化。希望它帮助。

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

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.