Advanced Recipe Search

Introduction: Making Recipe Search Smarter

Welcome back! In the last lesson, you learned how to build basic endpoints to retrieve recipes from your database, including fetching a single recipe by its ID and listing recipes with pagination. These are the building blocks of any recipe API.

Now, let’s take things a step further. Imagine you open a cooking app and want to find recipes that use only the ingredients you have in your kitchen. Or maybe you want to see the steps of a recipe as a list so you can follow them one by one. These features make your app much more helpful and user-friendly.

In this lesson, you’ll learn how to:

  • Search for recipes by a list of ingredients.
  • Return recipe steps as an array, not just a long string.

These skills will help you build a smarter, more flexible recipe API.

Quick Model Recap

Before we dive in, let’s quickly remind ourselves how our data is organized. This will help you understand how searching and filtering work.

  • Recipe: Each recipe has an id, a name, a steps field (which is a string with all the steps), and a list of ingredients.
  • Ingredient: Each ingredient has an id and a name. Ingredients are linked to recipes through a many-to-many relationship.
  • Review: Each review is linked to a recipe and has a rating.

Here’s a simplified look at the models (using SQLAlchemy):

Python
from sqlalchemy import Table, Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship, declarative_base

Base = declarative_base()

recipe_ingredient = Table(
    'recipe_ingredient',
    Base.metadata,
    Column('recipe_id', Integer, ForeignKey('recipe.id'), primary_key=True),
    Column('ingredient_id', Integer, ForeignKey('ingredient.id'), primary_key=True)
)

class Ingredient(Base):
    __tablename__ = 'ingredient'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    recipes = relationship('Recipe', secondary=recipe_ingredient, back_populates='ingredients')

class Recipe(Base):
    __tablename__ = 'recipe'
    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    ingredients = relationship('Ingredient', secondary=recipe_ingredient, back_populates='recipes')
    steps = Column(Text)
  • The recipe_ingredient table connects recipes and ingredients.
  • Each recipe can have many ingredients, and each ingredient can be used in many recipes.

This structure is important for searching recipes by ingredients.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal