0

PARTIALLY SOLVED - I changed the request from

requests.post(url, headers = headers, data = data)

to:

requests.post(url, headers = headers, json = data)

and now it works. I am not sure why...

Original Post:

The code I am using below continues to provide a response:

{"code":"422","details":"Unrecognized token 'adGroupId': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'"}

I am able to get a successful response with POSTMAN, and am failing to see the difference between this and my requests vscode attempts. FWIW, I simply copy the request body from the IDE and pasted it into POSTMAN as 'raw'.

My 'request' library failing attempts in the IDE:

headers = {
  "Amazon-Advertising-API-ClientId": clientid,
  "Authorization": access,
  "Amazon-Advertising-API-Scope":scope,
  "Content-Type": "application/json"
}

data = {
  "adGroupId":adgroupid,
  "keywords": [
    {
      "keyword": "mini bricks",
      "matchType": "exact"
    }
  ]
}

response = requests.post(
  'https://advertising-api.amazon.com/v2/sp/keywords/bidRecommendations',
  headers = headers,
  data = data
)
print(response.text)

My successful POSTMAN request headers and body:

Request Headers
Amazon-Advertising-API-ClientId: ...
Authorization: ...
Amazon-Advertising-API-Scope: ...
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: ...
Request Body
{
  "adGroupId":...,
  "keywords": [
    {
      "keyword": "mini bricks",
      "matchType": "exact"
    }
  ]
}
ah2Bwise
  • 82
  • 2
  • 17
  • The error text "was expecting" suggests that there was more to the error message. – jarmod Apr 15 '22 at 15:36
  • good point - I just revised it to include the full response. But either way, why is an identical request working in POSTMAN but not in my IDE? – ah2Bwise Apr 15 '22 at 15:39
  • Because it's not identical, we just don't know what the difference is yet. – jarmod Apr 15 '22 at 15:39
  • 1
    I just updated this - changed the 'requests' arg from 'data=' to 'json=' and now it functions correctly. It is this arg within the 'requests' library that was causing the issue. – ah2Bwise Apr 15 '22 at 16:10
  • I was going to propose that earlier but it's not clear why this would change things. The key [difference](https://stackoverflow.com/questions/26685248/difference-between-data-and-json-parameters-in-python-requests-package) between `data=` and `json=` afaik is that the latter auto-populates `Content-Type: application/json` while with the former you have to set the explicit header (which you appear to have done). Digging a [little deeper](https://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests), it also seems to convert the dict to a JSON string. – jarmod Apr 15 '22 at 16:29

0 Answers0