Random and Popular Recipes
Introduction: Enhancing User Experience with Dynamic Recipes
Welcome back! So far, you’ve learned how to build API endpoints that let users retrieve recipes, search by ingredients, and view recipe steps. These features are essential for any recipe app, but sometimes users want a little more excitement or guidance. For example, what if someone can’t decide what to cook and wants a random suggestion? Or maybe they want to see the most popular recipes based on ratings from other users.
In this lesson, you’ll learn how to add two new features to your cooking helper API:
- An endpoint that returns a random recipe
- An endpoint that returns the most popular recipes based on user ratings
These features make your app more interactive and helpful, giving users new ways to discover recipes.
Quick Recall: Retrieving and Filtering Recipes
Before we dive in, let’s quickly remind ourselves how we’ve been working with recipes so far.
Previously, you built endpoints to:
- List all recipes with pagination (so users don’t get overwhelmed by too many results at once)
- Retrieve a single recipe by its ID
- Search for recipes by ingredients
All of these endpoints use Flask for routing and SQLAlchemy to interact with the database. You’ve also learned how to format JSON responses so that the data is easy to use in any app.
Now, let’s build on these skills to add dynamic selection features.
Building the Random Recipe Endpoint
Let’s start by creating an endpoint that returns a random recipe. This is useful for users who want to try something new or can’t decide what to cook.
Step 1: Setting Up the Route
First, we need to define a new route in our Flask app. We’ll use the @routes.route decorator to create a GET endpoint at /api/recipes/random.
This sets up the endpoint, but it doesn’t do anything yet.
Step 2: Selecting a Random Recipe
To select a random recipe from the database, we use SQLAlchemy’s order_by(func.random()) method. This tells the database to shuffle the recipes and pick the first one.
Recipe.querystarts a query for all recipes..order_by(func.random())shuffles the order randomly..first()picks the first recipe from the shuffled list.
If there are no recipes in the database, recipe will be None.
