Dynamic Recipe Endpoints
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 the routing and dependency injection features of the new tool and interact with the database using session objects. You’ve also learned how to format responses as dictionaries, which are automatically converted to JSON.
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. We’ll use the @router.get 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 the order_by(func.random()) method. This tells the database to shuffle the recipes and pick the first one.
db.query(Recipe)starts 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.
