How to access all available routes of a REST API f

2019-09-13 02:55发布

问题:

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?

回答1:

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.



回答2:

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.