1

I am calling the Amazon Product Advertising API in Python to get data for certain products: https://webservices.amazon.com/paapi5/documentation/quick-start/using-sdk.html.

I import the API with:

from paapi5_python_sdk.api.default_api import DefaultApi
from paapi5_python_sdk.models.search_items_request import SearchItemsRequest
from paapi5_python_sdk.models.search_items_resource import SearchItemsResource

I call the API using this:

response = default_api.search_items(search_items_request)

Then I try to write the response object to a file using basic code:

with open('paapi_response.json', 'w') as outfile:
   outfile.write(response)

But I get the following error:

TypeError : write() argument must be str, not SearchItemsResponse

I don't want to convert it to string because I want to keep the exact response of the file. Is there any way to print the response object to a file just as it is?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
B. Latif
  • 54
  • 7
  • you can use json package https://docs.python.org/3/library/json.html#basic-usage – goku Sep 10 '20 at 18:46
  • A JSON object *is* a string. JSON is specifically designed to represent structured data as a string. You seem to have a misconception here. – mkrieger1 Sep 10 '20 at 18:49
  • Does this answer your question? [How do I write JSON data to a file?](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file) – mkrieger1 Sep 10 '20 at 18:50
  • @mkrieger1 right. but i need to be able to write the 'SearchItemsResponse' object to the file and the .write() method is not recognizing that as a string. – B. Latif Sep 10 '20 at 18:51
  • @mkrieger1 Thanks for the suggestion. But when I feed the 'response' to json.dumps I get an error saying "TypeError : Object of type 'SearchItemsResponse' is not JSON serializable." – B. Latif Sep 10 '20 at 18:56
  • I suggest to use pickle and save it to `.pkl` for saving objects. – goku Sep 10 '20 at 18:59
  • @goku I looked at Pickle. I could use it to serialize data to a file - which I don't want. How else could I use it here? – B. Latif Sep 10 '20 at 19:43

1 Answers1

1

The SearchItemsResponse has a to_dict method which recursively converts it to a nested dictionary/list data structure.1

This you can write to a file as JSON as shown in How do I write JSON data to a file?:

import json

# ...

with open('paapi_response.json', 'w') as outfile:
    json.dump(response.to_dict(), outfile)

1Reference: lines 112 to 137 in the file paapi5-python-sdk-example/paapi5_python_sdk/models/search_items_response.py from the Python SDK zip file downloaded from the page you have linked.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65