Day 16 of the Anvil Advent Calendar
Build a web app every day until Christmas, with nothing but Python!
A Merry Little Recipe Finder App
I built a simple recipe searching app using Anvil and Spoonacular’s food API. You can use the app below to find the perfect recipe for your Christmas meal! Or for any meal!
https://find-a-recipe.anvil.app
Using the Spoonacular API
The recipe search app is built on top of Spoonacular’s food API. To build the app, you just need to sign up for a free API key, which can then be stored in an Anvil Secret.
The following code on the Server side returns a list of recipe names and IDs based on a search query:
@anvil.server.callable
def search(query):
apikey = anvil.secrets.get_secret('api_key')
query = anvil.http.url_encode(query)
return anvil.http.request(f"https://api.spoonacular.com/recipes/complexSearch?apiKey={apikey}&query={query}", json=True)
To get information about the recipe such as its source and how long it takes to cook, the recipe ID is passed to the following fuction:
@anvil.server.callable
def get_info(recipe_id):
apikey = anvil.secrets.get_secret('api_key')
return anvil.http.request(f"https://api.spoonacular.com/recipes/{recipe_id}/information?apiKey={apikey}", json=True)
Building the UI
Now all that’s needed is a user interface to search for and display recipes. We added a TextBox and an event handler for when the user presses Enter in the TextBox. The event handler calls the search
server function and displays the recipe names and photos in a repeating panel:
def search_box_pressed_enter(self, **event_args):
"""This method is called when the user presses Enter in this text box"""
results = anvil.server.call('search', self.text_box_1.text)
self.repeating_panel_1.items = results['results']
Each item in the repeating panel is a link. When clicked, it calls the get_info
server function and triggers an alert with more information about the recipe:
def link_1_click(self, **event_args):
"""This method is called when the link is clicked"""
info = anvil.server.call('get_info', self.item['id'])
alert(content=Popup(info=info), large=True)
Anvil makes it easy to build a front-end for an API. To check out the source code for this app in more detail, you can clone the app using the link below:
Give the Gift of Python
Share this post: