I am trying to extract from this the product name, offer: price and shipping. status: OK
request_id: 9a63eee0-6c67-425b-93b2-56d003fe83cc
data:
products:
[0]
product_id: 610231264822022444
product_title: Arctic Glacier Ice
product_description: Arctic Glacier Premium Ice is produced using an inside-out freezing process that ensures a crystal-clear appearance and a taste-free quality. It is hard frozen to last longer, ensuring your beverages are kept cold without any alteration in flavor. Recognized by the International Packaged Ice Association, this product highlights the standard of excellence in ice. Made in the USA, Arctic Glacier Premium Ice is designed to complement any beverage without impacting its taste.
product_photos:
[0] https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcTGy0YhbFzj59PFvwzmllOFalDoDvAdXJORwb6jgkzi5hVBSmkYUY7x5YlZSGXd-kcPVbWoOACarSqZgK2oGamfOqXPIg0QIcCOq2ITquIlCClGh_WT7XRJ7AeD
[1] https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcRvHsMDMNHL_kCG_ix-ZVaEMoYNJJn_abJFhu1YedVvlHdv0–fQxXGx0XgeLz-T-2H9Yseu3QiVJkXAKkce5KGYDKulPnognEGdXyzeZbLdaCzIRzH_2-rs-QT
[2] https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcTF79vssclU7mKFqXfGVI4-jTrjkblWPr6Lkbfh4J4ew_wLljkinhwKwuFngzqawSuyPViTqw029Z6L49Ztash_x3EpsqKk545I3jtqcuL5hQlLsOyR3WbIyFEypA
product_attributes:
product_rating: 4.8
product_page_url: https://google.com/shopping/product/610231264822022444?gl=us&hl=en
product_offers_page_url: https://google.com/shopping/product/610231264822022444/offers?gl=us&hl=en
product_specs_page_url: https://google.com/shopping/product/610231264822022444/specs?gl=us&hl=en
product_reviews_page_url: https://google.com/shopping/product/610231264822022444/reviews?gl=us&hl=en
product_page_url_v2: https://www.google.com/search?ibp=oshop&q=ice&prds=catalogid:610231264822022444,gpcid:7285883141473199670,headlineOfferDocid:610231264822022444,imageDocid:2031113151221176971,mid:576462763825633599,mno:5,pvo:3,pvt:a,rds:PC_7285883141473199670%7CPROD_PC_7285883141473199670,sori:0&gl=us&hl=en
product_num_reviews: 539
product_num_offers: 128
typical_price_range:
[0] $4.59
[1] $5.79
offer:
offer_id: 17266978041913228739
offer_page_url: http://www.chefstore.com/p/arctic-glacier-ice-cubes-20-lb_1445074/?srsltid=AfmBOopZA4Wia_PMjmBQpUwtkwXVlI_PvQBZSx7OYky-Fs834HvqRithLDY
price: $3.99
shipping: None
on_sale: False
original_price: None
product_condition: NEW
store_name: US Foods Chef’store
store_rating: 0
store_review_count: 0
store_reviews_page_url: https://www.google.com/shopping/ratings/account/metrics?q=chefstore.com&c=US&v=19
store_favicon: https://encrypted-tbn2.gstatic.com/faviconV2?url=http://www.chefstore.com&client=SHOPPING&size=32&type=FAVICON&fallback_opts=TYPE,SIZE,URL
payment_methods: PayPal, Google Pay, Klarna accepted:: This is the code I am using:: from flask import Flask, request, render_template, jsonify
import requests
app = Flask(__name__)
# API endpoint and headers
API_URL = “https://real-time-product-search.p.rapidapi.com/search-v2”
HEADERS = {
“x-rapidapi-key”: “0120c8bf04msh6d5c29e42bb10bbp19620fjsne0230d695402”,
“x-rapidapi-host”: “real-time-product-search.p.rapidapi.com”
}
@app.route(“/”, methods=[“GET”, “POST”])
def index():
if request.method == “POST”:
# Get user input from form
query = request.form.get(“query”)
if not query:
return render_template(“index.html”, error=”Please enter a search query.”)
# API call
querystring = {
“q”: query,
“country”: “us”,
“language”: “en”,
“page”: “1”,
“limit”: “10”,
“sort_by”: “BEST_MATCH”,
“product_condition”: “ANY”
}
try:
response = requests.get(API_URL, headers=HEADERS, params=querystring)
response.raise_for_status() # Raise HTTPError for bad responses
json_data = response.json() # Parse JSON response
# Format JSON for display
formatted_data = format_json(json_data)
return render_template(“index.html”, data=formatted_data)
except requests.exceptions.RequestException as e:
return render_template(“index.html”, error=f”Error fetching data: {e}”)
return render_template(“index.html”)
def format_json(data, indent=0):
“””
Recursively formats JSON data into readable HTML with node names.
“””
if isinstance(data, dict):
formatted = “”
for key, value in data.items():
formatted += f”
”
return formatted
elif isinstance(data, list):
formatted = “”
for index, item in enumerate(data):
formatted += f”
”
return formatted
else:
return f”{data}”
if __name__ == “__main__”:
app.run(debug=True)
To extract the product name, offer price, and shipping status from the data provided, you can modify your existing Flask route and formatting functions. Here’s an approach to extract and display the specific details from the JSON response:
1. Update the `format_json` function to target the product details you’re interested in.
2. Include specific logic to extract `product_title`, `price`, and `shipping`.
Here’s an updated version of your code with that functionality:
“`python
from flask import Flask, request, render_template, jsonify
import requests
app = Flask(__name__)
# API endpoint and headers
API_URL = “https://real-time-product-search.p.rapidapi.com/search-v2”
HEADERS = {
“x-rapidapi-key”: “0120c8bf04msh6d5c29e42bb10bbp19620fjsne0230d695402”,
“x-rapidapi-host”: “real-time-product-search.p.rapidapi.com”
}
@app.route(“/”, methods=[“GET”, “POST”])
def index():
if request.method == “POST”:
# Get user input from form
query = request.form.get(“query”)
if not query:
return render_template(“index.html”, error=”Please enter a search query.”)
# API call
querystring = {
“q”: query,
“country”: “us”,
“language”: “en”,
“page”: “1”,
“limit”: “10”,
“sort_by”: “BEST_MATCH”,
“product_condition”: “ANY”
}
try:
response = requests.get(API_URL, headers=HEADERS, params=querystring)
response.raise_for_status() # Raise HTTPError for bad responses
json_data = response.json() # Parse JSON response
# Extract and format the necessary details
formatted_data = extract_product_details(json_data)
return render_template(“index.html”, data=formatted_data)
except requests.exceptions.RequestException as e:
return render_template(“index.html”, error=f”Error fetching data: {e}”)
return render_template(“index.html”)
def extract_product_details(data):
“””
Extracts the product title, offer price, and shipping status from the API response.
“””
formatted = “”
products = data.get(“products”, [])
for product in products:
product_title = product.get(“product_title”, “N/A”)
offers = product.get(“product_offers_page_url”, [])
if offers:
offer = offers[0] # Assuming first offer for now
price = offer.get(“price”, “N/A”)
shipping = offer.get(“shipping”, “N/A”)
formatted += f”
”
formatted += f”
”
formatted += f”
”
return formatted
if __name__ == “__main__”:
app.run(debug=True)
“`
### Key Updates:
– The `extract_product_details` function now extracts `product_title`, `price`, and `shipping` from the API response.
– It processes the product offers and returns these values in a simple HTML format.
– The `formatted_data` variable is updated to include only the relevant details (product name, offer price, and shipping).
### Notes:
– You might need to adapt the `shipping` extraction part depending on the actual structure of the `shipping` data in your API response (currently set to `”N/A”` as a placeholder).
Nothing is returning. Is the html right ::
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.error {
color: red;
margin-top: 10px;
}
.response {
margin-top: 20px;
white-space: pre-wrap;
font-family: monospace;
}
Real-Time Product Search
{% if error %}
{{ error }}
{% endif %}
{% if data %}
Response Data:
{{ data | safe }}
{% endif %}
Your HTML structure looks mostly correct, but there are a few things you can check and improve to ensure it works with Flask and displays the data as expected.
### Key Things to Check:
1. **Form submission**: Ensure the form submits correctly and the input is captured properly.
2. **Template rendering**: Ensure that the `data` passed from the Flask backend is rendered correctly in the template.
3. **Correct formatting in `extract_product_details` function**: If no data is being returned, make sure that the `data` passed to `format_json` or `extract_product_details` is correct.
### Suggested Fixes:
– **Ensure that the `extract_product_details` function is working**: You might want to print or log the response from the API to ensure that data is actually being fetched.
– **Return a fallback message** if no data is found in `extract_product_details`.
### Updated `index.html`:
This HTML should work, but let’s make a few enhancements to ensure the data is rendered cleanly:
“`html
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.error {
color: red;
margin-top: 10px;
}
.response {
margin-top: 20px;
white-space: pre-wrap;
font-family: monospace;
}
.product {
margin-bottom: 15px;
}
.product-title {
font-size: 1.2em;
font-weight: bold;
}
.product-info {
margin-top: 5px;
}
Real-Time Product Search
{% if error %}
{{ error }}
{% endif %}
{% if data %}
Response Data:
{% for item in data %}
{% else %}
No products found.
{% endfor %}
{% endif %}
“`
### Modifications in Flask Python Code:
To ensure that the data is passed correctly to the HTML template, modify the `extract_product_details` function so that it returns a list of dictionaries containing the necessary product data (`product_title`, `price`, and `shipping`), and the template will loop through it.
“`python
def extract_product_details(data):
“””
Extracts the product title, offer price, and shipping status from the API response.
“””
products = data.get(“products”, [])
extracted_data = []
for product in products:
product_title = product.get(“product_title”, “N/A”)
offers = product.get(“product_offers_page_url”, [])
if offers:
offer = offers[0] # Assuming first offer for now
price = offer.get(“price”, “N/A”)
shipping = offer.get(“shipping”, “N/A”)
extracted_data.append({
“product_title”: product_title,
“price”: price,
“shipping”: shipping
})
return extracted_data
“`
### Final Steps:
1. **Ensure API Response**: Add logging or print statements to check if `json_data` has the expected structure.
2. **Test the data flow**: After submitting a query, the response from the API should be displayed in the format you defined in the template.
This approach should correctly display the extracted product title, price, and shipping information on the webpage.