Python:对API的POST请求失败

mwngjboj  于 2023-02-21  发布在  Python
关注(0)|答案(2)|浏览(233)

我试图发送一个POST请求到Walmart API来请求报告。但是它用json返回了“Report request failed.”消息。我做错了什么?我真的没有太多python中API调用的经验。下面是我的代码。
我有一个名为“Walmart”的类来与Walmart Marketplace API交互,它有一些方法来通过API进行身份验证、发送请求和处理响应。

class Walmart(object):

    def __init__(self, client_id, client_secret):
        """To get client_id and client_secret for your Walmart Marketplace
        visit: https://developer.walmart.com/#/generateKey
        """
        self.client_id = client_id
        self.client_secret = client_secret
        self.token = None
        self.token_expires_in = None
        self.base_url = "https://marketplace.walmartapis.com/v3"

        session = requests.Session()
        session.headers.update({
            "WM_SVC.NAME": "Walmart Marketplace",
            "WM_QOS.CORRELATION_ID": uuid.uuid4().hex,
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
        })
        session.auth = HTTPBasicAuth(self.client_id, self.client_secret)
        self.session = session

        # Get the token required for API requests
        self.authenticate()

    def authenticate(self):
        data = self.send_request(
            "POST", "{}/token".format(self.base_url),
            body={
                "grant_type": "client_credentials",
            },
        )
        self.token = data["access_token"]
        self.token_expires_in = data["expires_in"]

        self.session.headers["WM_SEC.ACCESS_TOKEN"] = self.token

    @property
    def report(self):
        return Report(connection=self)

    def send_request(
        self, method, url, params=None, body=None, json=None,
        request_headers=None
    ):
        # A unique ID which identifies each API call and used to track
        # and debug issues; use a random generated GUID for this ID
        headers = {
            "WM_QOS.CORRELATION_ID": uuid.uuid4().hex,
            "WM_SVC.NAME": "Walmart Marketplace",
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
        }
        if request_headers:
            headers.update(request_headers)

        response = None
        if method == "GET":
            response = self.session.get(url, params=params, headers=headers)
        elif method == "PUT":
            response = self.session.put(
                url, params=params, headers=headers, data=body
            )
        elif method == "POST":
            request_params = {
                "params": params,
                "headers": headers,
            }
            if json is not None:
                request_params["json"] = json
            else:
                request_params["data"] = body
            response = self.session.post(url, **request_params)

        if response is not None:
            try:
                response.raise_for_status()
            except requests.exceptions.HTTPError:
                if response.status_code == 401:
                    raise WalmartAuthenticationError((
                        "Invalid client_id or client_secret. Please verify "
                        "your credentials from https://developer.walmart."
                        "com/#/generateKey"
                    ))
                elif response.status_code == 400:
                    data = response.json()
                    if "error" in data and data["error"][0]["code"] == \
                            "INVALID_TOKEN.GMP_GATEWAY_API":
                        # Refresh the token as the current token has expired
                        self.authenticate()
                        return self.send_request(
                            method, url, params, body, request_headers
                        )
                raise
        try:
            return response.json()
        except ValueError:
            # In case of reports, there is no JSON response, so return the
            # content instead which contains the actual report
            return response.content

这里是认证和请求本身。我想我用send_request方法做错了,我应该用不同的方法做吗?

api_key = '<key>'
api_secret='<secret>'
wm = Walmart(api_key, api_secret)
wm.authenticate()

url = "https://marketplace.walmartapis.com/v3/reports/reportRequests"
headers = {
      "WM_QOS.CORRELATION_ID": uuid.uuid4().hex,
       "WM_SVC.NAME": "Walmart Marketplace",
       "Content-Type": "application/x-www-form-urlencoded",
       "Accept": "application/json",
}
data= {
        "reportType": "ITEM_PERFORMANCE",
        "reportVersion": "v1",
}
method="POST"

response_dict = wm.send_request(method, url, request_headers=headers, params=data)

if 'status_code' in response_dict and response_dict['status_code'] == 200:
    response_json = response_dict.get('json')
    request_id = response_json.get('requestId')
    print(f'Report request submitted. Request ID: {request_id}')
else:
    print('Report request failed.')
    if 'json' in response_dict:
        print(response_dict['json'])
    else:
        print(response_dict)

我得到的回答是这样的。
报表请求失败。{“requestId”:“46 a864 e8 - 80 e8 -4019- 86 f0-d 7a 1575349 a4”,“请求状态”:“已接收”,“请求提交日期”:“2023年2月15日18:55:03 Z”,“报告类型”:“项目性能”,“报告版本”:'v1'}
任何帮助都很感激

vmdwslir

vmdwslir1#

您可以尝试打印响应以查看其内容,可能会有一些额外的信息帮助您修复代码。此外,您可以尝试使用此https://pypi.org/project/ipdb/逐行调试代码。

yqhsw0fo

yqhsw0fo2#

您得到的响应似乎是成功的响应,因为属性requestStatusRECEIVED,而不是ERROR(根据您链接的API文档,这是一个可能的值)。
因此,问题可能出在您的响应检查上。
根据您对响应的检查:

if 'status_code' in response_dict and response_dict['status_code'] == 200:
    response_json = response_dict.get('json')
    request_id = response_json.get('requestId')
    print(f'Report request submitted. Request ID: {request_id}')
else:
    print('Report request failed.')
    if 'json' in response_dict:
        print(response_dict['json'])
    else:
        print(response_dict)

'status_code' in response_dictresponse_dict['status_code'] == 200为假,这使得else块被执行。我建议您在if-else块之前访问print(response_dict),以查看整个内容,并查看这两个条件中的哪一个为假,然后相应地处理它。
我认为问题是您从wm.send_request()获得的对象不包含status_code,因为您获得的是响应的内容(当您使用return response.json()时),而不是来自requests库的session.Response对象(请参见文档)。

相关问题