@app.post("/gettopitems") async def gettopitems(): Assume "data" is the list of tuples…
- User
@app.post("/get_top_items") async def get_top_items(): # Assume "data" is the list of tuples you have after calling new_stats.get_top_sellers() data = stats.get_top_sellers() products = []
total_items = 0 for items in data: total_items += items[1]["number_in_stock"] # Sort the data based on "number_in_stock" in descending order sorted_data = sorted(data, key=lambda x: x[1]["number_in_stock"], reverse=True) # Get the top 10 items with the most stock top_10_products = sorted_data[:6] # Display the product names and their "number_in_stock" value for product, stats in top_10_products: procent_stock = (stats["number_in_stock"] / total_items) * 100 products.append(f"{product} {procent_stock:.2f}%") return productswill this fetch work?
getProductsSmall() { return fetch(
${host}get_top_items).then(res => res.json()).then(d => d.data); } - Assistant
The Python FastAPI function
get_top_itemsyou have defined seems to be intended to return the top items with the most stock. However, there are several issues with your code snippet, both in Python and JavaScript:Python Issues:
-
The
stats.get_top_sellers()might be a missing object and function call. You have mentionednew_stats.get_top_sellers()but usedstats.get_top_sellers(). Ensure you use the correct object and function to retrieve data. -
There is a logical error in your code—first, you are computing
total_itemsas the sum ofnumber_in_stock, but then you are usingnumber_in_stockfor sorting without consideringtotal_items. -
The endpoint does not specify a response model or format (such as
JSONResponse). FastAPI automatically serializes a Pythondictinto a JSON response, so you should ensure your response is adict.
Here is an example of how you could correct and improve the Python code:
from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse app = FastAPI() @app.post("/get_top_items") async def get_top_items(): data = stats.get_top_sellers() # Make sure stats is defined correctly products = [] total_items = sum(item[1]["number_in_stock"] for item in data) sorted_data = sorted(data, key=lambda x: x[1]["number_in_stock"], reverse=True) top_10_products = sorted_data[:10] # Corrected to actually get top 10 for product, stats in top_10_products: percent_stock = (stats["number_in_stock"] / total_items) * 100 products.append({"name": product, "percent_stock": f"{percent_stock:.2f}%"}) return JSONResponse(content=jsonable_encoder({"data": products}))JavaScript Issues:
- The
getProductsSmallfunction is trying to access a propertyd.datawhich might not correspond to the actual response structure. The response should match the structure the backend is sending.
Here is an example of how the JavaScript code should be adjusted once the API endpoint is fixed:
getProductsSmall() { return fetch(`${host}/get_top_items`, { method: 'POST', headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(d => d.data); // The response should have a data property according to the fixed Python code }Also, make sure to replace
${host}with the actual host address where your API is running.Ensure that both the backend and frontend are looking for and responding with the same data structure to avoid errors. If the API endpoint does not send a field named
data, the frontendgetProductsSmallfunction should not attempt to accessd.data. -