Struggling to "add to favorite" a restaurant from an API

Summary

Hi, I am a Python newbie and learning Streamlit for a project. I am using an external API to get restaurant data from a user’s preferred location, cuisine and rating. My idea is for streamlit to show the list of restaurants based on the criteria , user can favorite a restaurant by clicking a button, and all the data will be saved into a favorite_list which can be saved in a csv.file later on.

I have a problem:
I added an is_favorite : False criteria under my results for the restaurants details fetched, but Streamlit fails to update it to True (when I see it in my webpage) and also fails to extract and add it to a favorites list.

I have been experimenting with st.session_state and it seems like this is still erroneous for me.

Can you help me?

Steps to reproduce

Code snippet:

import requests
import streamlit as st
from config import API_Key

api_key = API_Key
headers = {'Authorization': f'Bearer {api_key}'}


def search_businesses(location, cuisine, rating):
    params = {'term': cuisine, 'location': location, 'rating': rating}
    response = requests.get('https://api.yelp.com/v3/businesses/search', headers=headers, params=params)
    data = response.json()
    if 'businesses' in data:
        businesses = data['businesses']
        results = []
        for business in businesses:
            categories = [category['title'] for category in business['categories']]
            if cuisine.lower() in [cat.lower() for cat in categories] and business.get('rating', 0) == float(rating):
                details = {}
                details['name'] = business['name']
                details['city'] = ''.join(business['location']['city'])
                details['address'] = ', '.join(business['location']['display_address'])
                details['rating'] = business.get('rating', 'N/A')
                details['price'] = business.get('price', 'N/A')
                details['phone'] = business.get('phone', 'N/A')
                details['review_count'] = business.get('review_count', 'N/A')
                details['cuisine'] = categories
                details['location'] = (business['coordinates']['latitude'], business['coordinates']['longitude'])
                details['url'] = business.get('url', 'N/A')
                details['is_favorite'] = False
                results.append(details)
    return results


def main():
    st.set_page_config(page_title='Yelp API Search')
    st.title('Yelp API Search')
    location = st.text_input('Location e.g., London', ' ')
    cuisine = st.text_input('Cuisine e.g., Mexican, Korean', ' ')
    rating = st.number_input('Rating (e.g. 3.5)', min_value=0.0, max_value=5.0, step=0.5)
    print('main function executed')
    "before clicking favorites", st.session_state
    favorite_restaurants = st.session_state.get('favorites', [])
     if st.button('Search'):
        results_data = search_businesses(location, cuisine, rating)
        st.subheader(f'Search results for {cuisine} in {location}:')
        if len(results_data) > 0:
            for result in results_data:
                st.write('Name:', result['name'])
                st.write('City:', result['city'])
                st.write('Address:', result['address'])
                st.write('Rating:', result['rating'])
                st.write('Price:', result['price'])
                st.write('Phone:', result['phone'])
                st.write('Review Count:', result['review_count'])
                st.write('Cuisine:', ", ".join(result['cuisine']))
                st.write('Location Coordinates:', result['location'])
                url = result['url']
                if url != 'N/A':
                    st.markdown(f'<a href="{url}" target="_blank">Website Link</a>', unsafe_allow_html=True)
                if st.button("Add to Favorites", key=result):
                    result['is_favorite'] = True
                    favorite_restaurants.append(result)
                st.write('---')
        st.session_state.favorites = favorite_restaurants
    st.write('Favorites:')
    if len(favorite_restaurants) == 0:
        st.write('No favorites yet.')
    else:
        for favorite in favorite_restaurants:
            st.write('Name:', favorite['name'])
            st.write('City:', favorite['city'])
            st.write('Address:', favorite['address'])
            st.write('Rating:', favorite['rating'])
            st.write('Price:', favorite['price'])
            st.write('Phone:', favorite['phone'])
            st.write('Review Count:', favorite['review_count'])
            st.write('Cuisine:', ", ".join(favorite['cuisine']))
            st.write('Location Coordinates:', favorite['location'])
            url = favorite['url']
            if url != 'N/A':
                st.markdown(f'<a href="{url}" target="_blank">Website Link</a>', unsafe_allow_html=True)
            st.write('---')
        st.session_state.favorites = favorite_restaurants
        print(favorite_restaurants)
        return favorite_restaurants



if __name__ == '__main__':
    main()




If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:
I expect that when I run this code, it will change the value of is_favorite to True when the"Add to Favorites" button is clicked, then it will be extracted and saved in the “favorite_restaurants” list which will eventually be saved in a CSV file.

Actual behavior:

is_favorite does not update
favorite_list is still empty.

Debug info

  • Streamlit version: 1.22.0
  • Python version: 3.10
  • Browser version: Chrome Version 113.0.5672.63 (Official Build) (64-bit)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.