1

我有一个像这样的 python 代码来与 API 交互

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import json
from pprint import pprint

key = "[SOME_KEY]"          # FROM API PROVIDER
secret = "[SOME_SECRET]"    # FROM API PROVIDER

api_client = BackendApplicationClient(client_id=key)
oauth = OAuth2Session(client=api_client)

url = "[SOME_URL_FOR_AN_API_ENDPOINT]"
# GETTING TOKEN AFTER PROVIDING KEY AND SECRET
token = oauth.fetch_token(token_url="[SOME_OAUTH_TOKEN_URL]", client_id=key, client_secret=secret)

# GENERATING AN OAuth2Session OBJECT; WITH THE TOKEN:
client = OAuth2Session(key, token=token)
body = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
response = client.post(url, data=json.dumps(body))
pprint(response.json())

当我运行这个 py 文件时,我从 API 得到这个响应,我必须在 header 中包含内容类型。如何在 Oauth2Session 中包含标头?

{'detailedMessage': 'Your request was missing the Content-Type header. Please '
                    'add this HTTP header and try your request again.',
 'errorId': '0a8868ec-d9c0-42cb-9570-59059e5b39a9',
 'simpleMessage': 'Your field could not be created at this time.',
 'statusCode': 400,
 'statusName': 'Bad Request'}
4

1 回答 1

3

您是否尝试过发送带有此请求的标头参数?

headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)
于 2019-12-03T15:11:58.760 回答