如何从控制器访问REST API的所有可用路由? [英] How to access all available routes of a REST API from a controller?

查看:180
本文介绍了如何从控制器访问REST API的所有可用路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Boot创建一个REST API,我想当用户向/help甚至只是向其根端点发出请求时,返回所有可用路由的列表(作为JSON).服务器,即就我而言,因为我在本地工作,所以localhost:8080.

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.

我知道我可以在例如Spring Boot应用程序启动时在日志中看到可用的路由,但是我不确定如何从Spring Boot控制器访问这些路由.就像我说的那样,这些路由将以JSON的形式返回,例如:

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", ... ]},
        ...
    ]

}

是的,我认为,通过这种方法,可以为尝试使用我创建的REST服务的客户端提供某种文档.

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?

推荐答案

您可以使用RequestMappingHandlerMapping

注入:

@Autowired
public RequestMappingHandlerMapping requestMappingHandlerMapping;

然后:

@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();
 }

应列出所有端点的URL路径.

Should list all endpoints URL path.

这篇关于如何从控制器访问REST API的所有可用路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆