Skip to content
beginner Phase · REST API Development

Sorting

Implement sorting parameters in REST API endpoints.

25m
0 problems
Topic Progress 0%

Sorting Patterns

Basic Sorting

GET /products?sort=price          → Sort by price (default: asc)
GET /products?sort=price:asc     → Sort by price ascending
GET /products?sort=price:desc    → Sort by price descending

Multiple Sort Fields

GET /products?sort=category:asc,price:desc,name:asc

# SQL Equivalent:
# ORDER BY category ASC, price DESC, name ASC

Common Sort Patterns

Pattern Example Notes
sort=field ?sort=name Simple, default asc
sort=field:direction ?sort=name:desc Explicit direction
sortBy=field&order=dir ?sortBy=name&order=desc Two params
order=field:dir ?order=name:desc Alternative

Sort Implementation

@GetMapping("/products")
public Page<Product> getProducts(
    @RequestParam(defaultValue = "createdAt") String sort,
    @RequestParam(defaultValue = "desc") String direction,
    Pageable pageable) {

    Sort.Direction dir = Sort.Direction.fromString(direction);
    Sort sortObj = Sort.by(dir, sort);
    Pageable sortedPageable = PageRequest.of(
        pageable.getPageNumber(),
        pageable.getPageSize(),
        sortObj
    );
    return productService.findAll(sortedPageable);
}

Sorting Best Practices

  1. Default sort — Always provide a default (e.g., createdAt desc)
  2. Whitelist fields — Only allow sorting on indexed fields
  3. Case sensitivity — Handle case-insensitive sorting
  4. Null handling — Define where nulls appear (first/last)

Best Practices

Key Principles

  1. Follow SOLID principles
  2. Write clean, readable code
  3. Test thoroughly
  4. Document decisions
  5. Monitor in production

Implementation

  • Start simple, refactor as needed
  • Use established patterns
  • Consider trade-offs
  • Review with peers

Continuous Improvement

  • Learn from incidents
  • Update documentation
  • Share knowledge
  • Mentor others

Key Points

  • Understanding Sorting is essential for production systems
  • Always consider scalability and maintainability
  • Test thoroughly before deploying to production
  • Monitor performance and set up alerting

Common Patterns

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0 / 3 solved
Implement Sorting

Design and implement a solution for Sorting in a backend system. Consider scalability, error handling, and production readiness.

Solution
// Sorting implementation
// Key aspects: validation, error handling, logging, testing

public class Sorting {
    // Production-ready implementation
}
Sorting Edge Cases

Identify and handle edge cases for Sorting. What happens under high load, with invalid input, or during failures?

Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotency
Sorting Testing Strategy

Write a testing strategy for Sorting. Include unit tests, integration tests, and performance tests.

Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injection

Quiz

1. What is the most common sort URL pattern?

Question 1 options

2. Why should you whitelist sortable fields?

Question 2 options

3. What is a common mistake when implementing Sorting?

Question 3 options

Flashcards

Question

Common sort URL pattern?

Answer

?sort=field:asc or ?sort=field:desc

Question

Why whitelist sortable fields?

Answer

Security (prevent info leak) + performance (use indexes)

Question

Sorting best practices

Answer

Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.

Revision Notes

Key Takeaways

  • 1. Use sort=field:direction pattern for sorting
  • 2. Always provide a default sort order
  • 3. Whitelist allowed sort fields for security and performance
  • 4. Support multiple sort fields

Interview Tips

  • Design sorting parameters
  • Explain why field whitelisting matters

Cheat Sheet

Sorting

  • Pattern: ?sort=field:asc or ?sort=field:desc
  • Multiple: ?sort=category:asc,price:desc
  • Default: Always provide (e.g., createdAt desc)
  • Security: Whitelist sortable fields