【问题标题】:How to Pass in an OAUTH Token Correctly如何正确传递 OAUTH 令牌
【发布时间】:2022-02-01 21:41:19
【问题描述】:

我正在尝试从 API 请求信息。 我认为我传递 OAUTH 令牌的方式是错误的。

import requests
import json

URL = "https://api.direct.yandex.com/json/v5/keywords"
token = "/* Access Token */"

PARAMS = {
           'Authorization': "Bearer " + token,
           'Accept-Language': "en",
           'processingMode': "auto",
}
BODY = {
           'method': "CreateNewWordstatReport",
           'param': {
                "Phrases": ['pipeline'],
                "GeoID": [1,-219]
                }
           }

#jdata = json.dumps(PARAMS, ensure_ascii=False).encode ('utf8')

body = json.dumps(BODY, indent=4)
response = requests.post(URL, body, headers=PARAMS)
response.encoding = 'utf-8'

#response = requests.get(url = URL, params = PARAMS)

print(response.status_code)
print(response.url)
print(response.json())

注释行是中间三行的潜在替代品。如何在此处正确使用 .post() 和 .get() 以传递令牌? 显示当前响应:

202

https://api.direct.yandex.com/json/v5/keywords

{'error': {'request_id': '1891/* 更多数字 */0199', 'error_code': 8000, 'error_detail': '无法处理 JSON/XML', 'error_string': '无效请求'}}

非常感谢您的帮助!

【问题讨论】:

    标签: oauth-2.0 oauth python-requests python-requests-html yandex-api


    【解决方案1】:

    您是否在 Postman 中尝试过相同的操作?如果没有,建议在那里尝试相同的方法并使用“代码”选项来获取构建的代码示例。以下是其中一个示例中用于传递 Oauth 令牌的代码:

    import requests
    import json
    
    url = "<url>"
    
    payload = json.dumps({<Body>
    })
    headers = {
      'Accept-Charset': 'utf-8',
      'Accept-Encoding': 'utf-8',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer <token-value>'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多