What are the considerations when using @PathVariable in terms of URL design?

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

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.

Last updated: 16 July 2026

Previous question: How can you extract values from a URL using @PathVariable?

Next question: How does @PathVariable interact with other request mappings in Spring MVC?

More Spring MVC (Optional) interview questions

All Spring MVC (Optional) questions