1

I am using python request library to interact with API.

import requests

url = "https://amazon24.p.rapidapi.com/api/product"

querystring = {"keyword":"iphone","country":"US","page":"1"}

headers = {
    'x-rapidapi-host': "amazon24.p.rapidapi.com",
    'x-rapidapi-key': "key"
    }

response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)

Response I am getting is something like this. I have only included first few lines of response as it is too long.

{"docs":[{"isBestSeller":false,"product_title":"Apple iPhone XR (64GB, (PRODUCT)RED) [Locked] + Carrier Subscription","product_main_image_url":"https://m.media-amazon.com/images/I/51YXG1bDM5L._AC_UY218_.jpg","app_sale_price":"499.00","app_sale_price_currency":"$","isPrime":true,"product_detail_url":"https://www.amazon.com/dp/B07VSWLY55","product_id":"B07VSWLY55","evaluate_rate":"4.2 out of 5 stars","original_price":null},{"isBestSeller":false,"product_title":"New Apple iPhone 12 Mini (64GB, Black) Unlocked","product_main_image_url":"https://m.media-amazon.com/images/I/71uuDYxn3XL._AC_UY218_.jpg","app_sale_price":"729.00","app_sale_price_currency":"$","isPrime":true,"product_detail_url":"https://www.amazon.com/dp/B096R76SFK","product_id":"B096R76SFK","evaluate_rate":"4.2 out of 5 stars","original_price":null}}}]}}}

My question is how can I extract attributes like "product_title" or "app_sale_price" from above response. Desperately need help. Thanks

1
  • response.json() will return a dict. Commented Sep 13, 2021 at 10:36

2 Answers 2

4

You can convert the response to a dictionary using response.json().

Following that, you can access the various attributes such as data["docs"][0]["product_title"]

An example is as follows:

data = response.json()
for doc in data["docs"]:
    print(doc["product_title"], doc["app_sale_price"])

You can learn more about dictionaries here (official python docs) or here (w3schools)

Sign up to request clarification or add additional context in comments.

Comments

1

Your response is JSON, requests has handy method for such situation, just do

response = requests.request("GET", url, headers=headers, params=querystring)
response_data = response.json()

then response_data is python object, dict in your case and you might do for example

titles = [i.get("product_title") for i in response_data["docs"]]
print(titles)

to get titles from list of dicts present under key "docs"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.