How to Handle Sub-Resources in REST APIs Correctly
/users/{userId}/orders for orders of a specific user. Use appropriate HTTP methods on these URLs to manage sub-resources clearly and consistently.Why This Happens
Developers sometimes treat sub-resources as separate top-level resources, ignoring their relationship to parent resources. This causes unclear URLs and makes it hard to manage related data properly.
For example, trying to access orders without specifying the user can lead to confusion about which user's orders are requested.
GET /orders/123 // This URL does not show which user owns order 123, causing ambiguity.
The Fix
Use nested URLs to show the relationship between resources clearly. For example, to get order 123 of user 45, use /users/45/orders/123. This makes the API intuitive and RESTful.
Use HTTP methods like GET, POST, PUT, DELETE on these nested URLs to manage sub-resources properly.
GET /users/45/orders/123 POST /users/45/orders PUT /users/45/orders/123 DELETE /users/45/orders/123
Prevention
Always design your API URLs to reflect resource hierarchy. Use nested paths for sub-resources to keep relationships clear.
Document your API structure so users understand how to access sub-resources.
Use consistent naming and HTTP methods to avoid confusion.
Related Errors
Common mistakes include using query parameters instead of nested URLs for sub-resources, like /orders?userId=45, which is less clear.
Another error is mixing resource IDs without hierarchy, causing ambiguous endpoints.
GET /orders?userId=45 // Less clear than nested URL approach