0
0
Rest APIprogramming~30 mins

Sparse fieldsets (select fields) in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Sparse Fieldsets (Select Fields) in REST API
📖 Scenario: You are building a REST API for a library system. The API returns information about books. Sometimes, clients want only specific fields of the book data to reduce the amount of data transferred.
🎯 Goal: Build a simple REST API endpoint that returns book data. Add support for sparse fieldsets so clients can request only selected fields of each book.
📋 What You'll Learn
Create a list of dictionaries representing books with exact fields: id, title, author, year, genre
Create a variable requested_fields that holds a list of fields to include in the response
Write code to filter each book dictionary to include only the requested fields
Print the filtered list of books as the API response
💡 Why This Matters
🌍 Real World
APIs often allow clients to request only the data fields they need to reduce bandwidth and improve performance.
💼 Career
Understanding sparse fieldsets is important for backend developers building efficient and flexible REST APIs.
Progress0 / 4 steps
1
Create the initial book data
Create a list called books with exactly three dictionaries. Each dictionary must have these keys and values:
1. {'id': 1, 'title': '1984', 'author': 'George Orwell', 'year': 1949, 'genre': 'Dystopian'}
2. {'id': 2, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'year': 1960, 'genre': 'Fiction'}
3. {'id': 3, 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'year': 1925, 'genre': 'Classic'}
Rest API
Need a hint?
Make sure to create a list named books with exactly three dictionaries having the specified keys and values.
2
Set the requested fields to include
Create a list called requested_fields with these exact strings: 'id', 'title', and 'year'.
Rest API
Need a hint?
Make sure requested_fields is a list with exactly 'id', 'title', and 'year'.
3
Filter books to include only requested fields
Create a new list called filtered_books. Use a for loop with variable book to go through books. For each book, create a dictionary that includes only keys from requested_fields. Add this dictionary to filtered_books.
Rest API
Need a hint?
Use a for loop and dictionary comprehension to select only requested fields from each book.
4
Print the filtered books as API response
Write a print statement to display the filtered_books list.
Rest API
Need a hint?
Use print(filtered_books) to show the final filtered list.