Search code examples
pythonjsonapipaapi

Saving Amazon PA API response to JSON file using Python SDK


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?


Solution

  • 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.