0
0
Rest APIprogramming~30 mins

Filtering by field values in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Filtering by field values
📖 Scenario: You are building a simple REST API that returns a list of books. Users want to filter books by their genre.
🎯 Goal: Create a REST API endpoint that returns only books matching a given genre filter.
📋 What You'll Learn
Create a list of books with exact fields and values
Add a variable to hold the genre filter
Filter the books list by the genre field using the filter variable
Return the filtered list as JSON output
💡 Why This Matters
🌍 Real World
Filtering data by field values is common in APIs to let users get only the data they want.
💼 Career
Backend developers often write code to filter database or API data based on user requests.
Progress0 / 4 steps
1
Create the initial list of books
Create a list called books with these exact dictionaries: {'title': 'The Hobbit', 'genre': 'Fantasy'}, {'title': '1984', 'genre': 'Dystopian'}, {'title': 'To Kill a Mockingbird', 'genre': 'Classic'}, {'title': 'The Great Gatsby', 'genre': 'Classic'}
Rest API
Need a hint?
Make sure to create a list named books with dictionaries for each book as shown.
2
Add a genre filter variable
Create a variable called genre_filter and set it to the string 'Classic'
Rest API
Need a hint?
Set genre_filter exactly to the string 'Classic'.
3
Filter the books by genre
Create a new list called filtered_books that contains only the books from books where the 'genre' field equals genre_filter
Rest API
Need a hint?
Use a list comprehension to filter books by comparing book['genre'] to genre_filter.
4
Print the filtered books as JSON
Import the json module and print the filtered_books list as a JSON string using json.dumps(filtered_books)
Rest API
Need a hint?
Use json.dumps to convert filtered_books to a JSON string and print it.