dev_tech
dev_tech

Reputation: 47

Displaying a List of Data from in Flask REST API Python

In my REST API I have the following code

i = 0
for item in similar_items:
    name= main.get_name_from_index(item [0])
    url = main.get_url_from_index(item [0])

    category = main.get_categories_from_index(item [0])

    if (name!= None):
        
        return {'Name': name, 'Category': category, 'URL': url }, 200  # return data and 200 OK code
        i = i + 1
        if i > 20:
            break 

This essentially intends to iterate through similar_items and to print out the top 20 however currently it only send the JSON object of the first one. I believe the problem is with the return statement but no matter where I place it I run into the same problem.

Would really appreciate if anyone can share how I can return the desired amount of objects instead of the first one.

Upvotes: 0

Views: 550

Answers (1)

Adam Oellermann
Adam Oellermann

Reputation: 303

Your code above is returning a dictionary containing a single item, where it seems like it should be returning a list of such dictionaries. Try something like this:

i = 0

results = [] # prepare an empty results list

for item in similar_items:
    name= main.get_name_from_index(item [0])
    url = main.get_url_from_index(item [0])

    category = main.get_categories_from_index(item [0])

    if (name!= None):
        results.append({'Name': name, 'Category': category, 'URL': url }) # add the current item into the results list
        i = i + 1
        if i > 20: # NB if you want 20 items this should be >= not just > :-)
            return results, 200  # return data and 200 OK code
            break 

Upvotes: 1

Related Questions