Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access all available routes of a REST API from a controller?

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?

like image 520
nbro Avatar asked Dec 01 '22 12:12

nbro


2 Answers

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.

like image 50
Thomas Decaux Avatar answered Dec 05 '22 09:12

Thomas Decaux


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.

like image 25
Marcos Echagüe Avatar answered Dec 05 '22 09:12

Marcos Echagüe