CodePark/ questions / Pagination, filtering & versioning
START PRACTICINGPRACTICE
Backend question · HTTP & API design › Pagination, filtering & versioning

How would you design filtering and sorting query parameters for GET /products?

GET /products?category=books&minPrice=10&sort=-price,name&limit=20

Use query parameters. Filters only narrow down a collection. They do not point to a new resource, so they don't belong in the path.

Common conventions:

  • Simple equality filters map a field to a value, like category=books.
  • Ranges use clear names, like minPrice and maxPrice.
  • Sorting often uses a comma-separated list, with - for descending order. So sort=-price,name means price from high to low, then by name.

Validate everything:

  • Allow only known fields for filters and sorting. This is an allowlist.
  • Check the type of each value.
  • Cap limit at a maximum value.
  • Return 400 for unknown parameters or bad values. Don't silently ignore them.

The allowlist also has a safety benefit. It stops clients from sorting on columns without an index, which would make queries slow. It also stops them from injecting code into your queries.

Return pagination information with the results, such as a next link or a cursor. Document the conventions once, and use them on every collection.

  • Filters and sorts go in query parameters.
  • Use consistent conventions, such as - for descending order.
  • Allowlist the fields and validate the types.
  • Cap limit, and reject bad input with a 400 status.