如何用 Spring 自我描述 REST api?

How to self describe a REST api with Spring?

我正在使用 spring-mvc 创建 servlet,例如:

@RestController
public class MyServlet {
   @GetMapping("/test")
   public MyRsp test(MyReq req) {
         //...
   }
}

现在,如果用户访问我的应用程序 localhost:8080/my-app 的根目录,它应该会显示可用的 GETPOST 方法列表。最好有可能的输入参数,可接受的 headers 等

问题:是否可以使用任何 spring 框架,例如 HATEOAS

我希望框架能够自动检测任何 @RestController 和包含的方法。

或者我必须自己创建概览页面吗?

您可以查看此项目 Spring Restdocs (github),它允许您生成随时可用的 REST 文档。它由 Spring Team:

官方维护

The primary goal of this project is to make it easy to document RESTful services by combining content that's been hand-written using Asciidoctor with auto-generated examples produced with the Spring MVC Test framework. The result is intended to be an easy-to-read user guide, akin to GitHub's API documentation for example, rather than the fully automated, dense API documentation produced by tools like Swagger.

另一种选择是使用Swagger,它也支持自下而上的方法:

A bottom-up approach where you have an existing REST API for which you want to create a Swagger definition. Either you create the definition manually (using the same Swagger Editor mentioned above), or if you are using one of the supported frameworks (JAX-RS, node.js, etc), you can get the Swagger definition generated automatically for you.

这里提到了一些招摇的例子:1 2

Swagger 2 是另一种选择。阅读以下内容以了解有关 swagger 及其设置方法的更多信息。

Setting Up Swagger 2 with a Spring REST API

您还可以为您的其余 api 创建 swagger 定义,客户端可以使用它来生成客户端 类.

此外,swagger ui 可用于 test/invoke 您的 API。 swagger 提供了一个用户界面,您可以在其中输入所有 api 输入,例如查询参数、路径参数、请求 body、headers。

Sample Swagger UI

你应该看看 this

整合到spring可以参考this

Swagger 是公开 RESTful API 的最佳框架之一。