Anurag Sharma
Anurag Sharma

Reputation: 2605

REST API: variable path variables

How can I create a single REST API for variable number of path variables such as GET "/ads/{category1}/.../{categoryN}" in Spring?

where number of categories is not fixed

Upvotes: 1

Views: 221

Answers (1)

Elyor Murodov
Elyor Murodov

Reputation: 1028

It's not provided out-of-the-box by Spring, but there is some workaround.

You can map any path like "/ads/**" to your handler method, and then parse categories by splitting the rest of the path by slash:

String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String tailPath = path.substring(5); //skip "/ads/"
String[] categories = tailPath.split("/");

Upvotes: 1

Related Questions