0

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.

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

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.