I'm creating a REST API using Spring Boot, and I thought to return a list (as JSON) of all available routes when the user makes a request to, say, /help
or even simply to the root endpoint of the server, i.e., in my case since I'm working locally, localhost:8080
.
I know I can see the available routes in the logs when, e.g., the Spring Boot application starts, but I'm not sure how can I access these routes from a Spring Boot controller. As I said, these routes would be returned as JSON, something like:
{
routes: [
"/api/users/create",
"/api/users/list",
...
]
}
of course, it would also be nice to provide additional required information to make the requests to the specific URLs, e.g. if the client needs to pass certain request parameters, which ones, and in which format.
For example, it would be something of the form:
{
"routes" : [
{"route": /api/users/create", "requestParams": ["name", "age", ... ]},
...
]
}
Yes, I thought, with this method, to provide some kind of documentation to a client trying to use the REST services which I created.
How can I do this? Is there a simple way at least of accessing the routes?
Would there be any problems in doing this? If yes, which ones?
You can use RequestMappingHandlerMapping
Inject it:
@Autowired
public RequestMappingHandlerMapping requestMappingHandlerMapping;
Then:
@RequestMapping("/endpoints")
public @ResponseBody
Object showEndpointsAction() throws SQLException
{
return requestMappingHandlerMapping.getHandlerMethods().keySet().stream().map(t ->
(t.getMethodsCondition().getMethods().size() == 0 ? "GET" : t.getMethodsCondition().getMethods().toArray()[0]) + " " +
t.getPatternsCondition().getPatterns().toArray()[0]
).toArray();
}
Should list all endpoints URL path.
Do you consider the possibility to use Swagger for give a documentation for you API? is simple to use, with some annotations you will have a complete documentation for you API. Here you have a guide how to configure Swagger. I hope that it help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With