Sub-resources vs Query Parameters
What you'll learn: You'll understand when to model data as nested paths versus filtering collections with query strings in REST APIs.
When designing REST APIs, you often need to retrieve data that relates to a specific parent resource. Should you use a nested path like /users/123/orders or a query parameter like /orders?userId=123? The choice matters for clarity and maintainability.
Sub-resources: Showing Ownership or Strong Relationship
Use sub-resources (nested paths) when the child resource is tightly bound to the parent and rarely makes sense on its own. The relationship is part of the resource's identity.
Example: /users/123/orders
This says "give me the orders that belong to user 123." The orders are conceptually owned by or scoped to that specific user. The path reads naturally: "user 123's orders."
Query Parameters: Filtering a Collection
Use query parameters when you're filtering or searching across a broader collection. The filter is just one of many possible criteria, and the resource exists independently.
Example: /orders?userId=123&status=shipped
This says "give me all orders, filtered by user ID and status." Orders exist as a standalone resource; you're simply narrowing down the results. You might add other filters like ?date=2024-01-01 without changing the fundamental resource.
The Guideline
Ask yourself: "Is this child resource primarily defined by its parent, or is it an independent collection I'm filtering?"
- Strong ownership → sub-resource (
/users/123/orders) - Filtering/searching → query parameter (
/orders?userId=123)
Key Takeaway: Use sub-resources for parent-owned relationships where the child belongs to that parent; use query parameters when filtering independent collections by various criteria.