0
0
Rest APIprogramming~30 mins

Sorting with sort parameter in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting with sort parameter in REST API
📖 Scenario: You are building a simple REST API that returns a list of products. Users want to get the products sorted by price or name.
🎯 Goal: Create a REST API endpoint that returns a list of products sorted by a query parameter called sort. The sort parameter can be either price or name. If no sort parameter is given, return the products unsorted.
📋 What You'll Learn
Create a list of products with exact entries
Add a variable to read the sort parameter
Sort the products list by the sort parameter if it is price or name
Return the sorted or unsorted list as JSON
💡 Why This Matters
🌍 Real World
Sorting data by user preference is common in online stores and APIs to improve user experience.
💼 Career
Understanding how to handle query parameters and sort data is essential for backend developers working with REST APIs.
Progress0 / 4 steps
1
DATA SETUP: Create the products list
Create a list called products with these exact dictionaries: {'name': 'Apple', 'price': 5}, {'name': 'Banana', 'price': 2}, {'name': 'Cherry', 'price': 7}
Rest API
Need a hint?

Use a list of dictionaries with the exact keys and values.

2
CONFIGURATION: Read the sort parameter
Create a variable called sort_param that reads the sort query parameter from request.args.get('sort')
Rest API
Need a hint?

Use request.args.get('sort') to get the query parameter.

3
CORE LOGIC: Sort the products list by the sort parameter
If sort_param is 'price', sort products by the 'price' key. If sort_param is 'name', sort products by the 'name' key. Use the sort() method with a key argument.
Rest API
Need a hint?

Use products.sort(key=lambda product: product['price']) to sort by price.

4
OUTPUT: Return the sorted or unsorted products as JSON
Use print(products) to display the final products list.
Rest API
Need a hint?

Use print(products) to show the list.