Python 从 REST 请求令牌 API

Python Request Token from REST API

我正在努力处理这份文档 here

以这个请求为例:

**Header**

“`json

{

‘Content-Type’: ‘application/x-www-form-urlencoded’,

‘authorization’: ‘Basic <base64 encoded username:password>’

 }

 “`

 **Body**

 “`json

 {

 ‘grant_type’: ‘client_credentials’

 }

 “`

如何将 with 变成 requests.post() ?

您必须构建字典并 post 它们带有请求:

import requests
import base64
import json

username = "user"
password = "password"
url = 'https://myurl.com'

headers = {}
headers['Content-Type'] = 'application/x-www-form-urlencoded'
headers['authorization'] = 'Basic ' + base64.b64encode(bytes(username + ':' + password, 'utf-8')).decode('utf-8')

body = {}
body['grant_type'] = 'client_credentials'

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