在Python中获取Oauth访问令牌

时间:2017-11-16 22:39:28

标签: python curl oauth-2.0 python-requests

我正在尝试为实验的沙盒API生成oauth访问令牌(它们提供有关信用信息的信息)。 他们的tutorial表示运行此(假数据)以获取访问令牌:

curl -X POST
-d '{ "username":"youremail@email.com", "password":"YOURPASSWORD"}'
-H "Client_id: 3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9"
-H "Client_secret: ipu3WQDqTEjqZDXW"
-H "Content-Type: application/json"
"https://sandbox-us-api.experian.com/oauth2/v1/token"

我如何在python中运行它?我在很多其他事情中尝试过这个:

data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"}

headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"}

response = requests.post("https://sandbox-us-
api.experian.com/oauth2/v1/token", data=data, headers=headers)

非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

几乎就在那里,只需要解析响应:

import json

data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"}

headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"}

response = requests.post("https://sandbox-us-api.experian.com/oauth2/v1/token", data=data, headers=headers)
if response.status_code in [200]:
    tok_dict = json.loads(response.text)
    print(tok_dict)
    issued_at = tok_dict["issued_at"]
    expires_in = tok_dict["expires_in"]
    token_type = tok_dict["token_type"]
    access_token = tok_dict["access_token"]
else:
    print(response.text)