Sort Python list by query param order_by
Sort a list of dataclass objects dynamically by a field name passed as a query param, with asc/desc direction support.
Python code
28 linesfrom dataclasses import dataclass
@dataclass
class Item:
name: str
price: int
def sort_items(items, order_by, direction="asc"):
if order_by not in ("name", "price"):
raise ValueError(f"Unsupported sort field: {order_by}")
reverse = direction.lower() == "desc"
return sorted(items, key=lambda item: getattr(item, order_by), reverse=reverse)
if __name__ == "__main__":
inventory = [
Item("banana", 3),
Item("apple", 5),
Item("cherry", 2),
]
print("Asc by name:", [item.name for item in sort_items(inventory, "name")])
print("Desc by name:", [item.name for item in sort_items(inventory, "name", "desc")])
print("Asc by price:", [item.name for item in sort_items(inventory, "price")])
print("Desc by price:", [item.name for item in sort_items(inventory, "price", "desc")])
Output
Asc by name: ['apple', 'banana', 'cherry']
Desc by name: ['cherry', 'banana', 'apple']
Asc by price: ['cherry', 'banana', 'apple']
Desc by price: ['apple', 'banana', 'cherry']
How it works
The sort_items function uses getattr to fetch the sort attribute dynamically from each Item instance, based on the order_by parameter. Allowing only whitelisted field names prevents arbitrary attribute access and potential errors. The reverse flag flips the sort direction when the query parameter is 'desc', matching common API conventions. Using dataclasses keeps the data structure lightweight and readable.
Common mistakes
- Letting user input access internal attributes like `_private_field` through `getattr` without a whitelist.
- Case-sensitive comparison of direction (expecting 'DESC' to work).
- Forgetting to validate the sort field before calling `sorted`, causing a generic AttributeError instead of a friendly 400 error.
Variations
- Use a lambda with explicit if/elif instead of `getattr` for more complex sort keys.
- Sort in-place with `list.sort()` if the original order is not needed.
Real-world use cases
- Implementing a REST API endpoint like GET /items?order_by=price&direction=desc to let clients control response ordering.
- Building an admin panel that sorts tables by clicking column headers, sending the sort field as a query parameter.
- Sorting an in-memory cache or test fixture data in a deterministic order before asserting API responses.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.