如何添加 http headers 以及数据以使用 Oauth2Session (requests_oauthlib) 将 POST 请求发送到 API 端点?
How to add http headers along with data to send a POST request to an API endpoint using Oauth2Session (requests_oauthlib)?
我有这样的 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。如何将 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'}
您是否尝试过使用此请求发送 header 参数?
headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)
我有这样的 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。如何将 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'}
您是否尝试过使用此请求发送 header 参数?
headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)