When designing URLs that use @PathVariable, the goal is a resource-oriented, predictable structure where each path segment clearly identifies what it represents. Poor path variable naming or placement leads to ambiguous routes and mapping conflicts between controllers.
Key Points: • Name path variables descriptively, such as {userId} or {orderId}, instead of generic names like {id} when a controller handles multiple resource types. • Keep URLs hierarchical and resource-based, e.g. /users/{userId}/orders/{orderId}, mirroring the relationship between entities. • Avoid ambiguous overlaps between a fixed segment and a variable segment, such as /users/new colliding with /users/{userId} when "new" is passed as an ID. • Keep path variables limited to identifiers; use query parameters (@RequestParam) for optional filters, sorting, or pagination instead of stuffing them into the path. • Ensure uniqueness and consistency of mapping patterns across the application so Spring can resolve requests to exactly one handler.
Example: For a blog API, /posts/{postId}/comments/{commentId} clearly expresses that a comment belongs to a post, and is far less ambiguous than a flat structure like /getCommentByIds/{a}/{b}.
Interview Tip: A concise interview answer is:
"I treat path variables as resource identifiers, so I name them descriptively like {userId} and structure URLs hierarchically to reflect entity relationships. I'm also careful to avoid collisions between literal path segments and variable ones, and I push optional filters into query parameters instead of the path."