与时俱进:在JAX-RS API中采用OpenAPI v3.0.0
看到时间流逝真是太恐怖了! OpenAPI规范3.0.0是对Swagger规范的重大修改,大部分已于一年前发布,但是工具赶上了一段时间。 但是,随着Swagger Core 2.0.0的最新正式发布,事情肯定会加速。
为了证明这一点,著名的JAX-RS 2.1实现Apache CXF是OpenAPI 3.0.0的最早采用者之一,在今天的帖子中,我们将了解一下JAX-RS 2.1 API可以多么容易从中受益。
与往常一样,为了使事情变得简单,我们将设计人员管理Web API,仅提供少量支持它的资源,这里没有什么太令人兴奋的。
POST /api/people
GET /api/people/{email}
GET /api/people
DELETE /api/people/{email}
我们的模型将包含一个Person类。
public class Person {private String email;private String firstName;private String lastName;
}
为了增加一点魔力,我们将使用Spring Boot来使我们尽快启动并运行。 这样,让我们开始填充依赖项(假设我们使用Apache Maven进行构建管理)。
<dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxrs</artifactId><version>3.2.4</version>
</dependency>
在最近的3.2.x版本中, Apache CXF基于Swagger Core 2.0.0引入了一个专门用于OpenAPI 3.0.0的新模块cxf-rt-rs-service-description-openapi-v3 。
<dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-rs-service-description-openapi-v3</artifactId><version>3.2.4</version>
</dependency><dependency><groupId>org.webjars</groupId><artifactId>swagger-ui</artifactId><version>3.13.6</version>
</dependency>
Swagger UI的存在不是绝对必要的,但是它是探索API的非常有用且漂亮的工具(如果在classpath中可用, Apache CXF会将其无缝集成到您的应用程序中,我们将在稍后介绍) 。
前提条件就位,让我们做一些编码! 在开始之前,值得注意的是Swagger Core 2.0.0有很多方法可以为您的服务填充OpenAPI 3.0.0定义,包括属性文件,注释或以编程方式。 在这篇文章中,我们将仅使用注释。
@OpenAPIDefinition(info = @Info(title = "People Management API",version = "0.0.1-SNAPSHOT",license = @License(name = "Apache 2.0 License",url = "http://www.apache.org/licenses/LICENSE-2.0.html"))
)
@ApplicationPath("api")
public class JaxRsApiApplication extends Application {
}
看起来非常简单, @ OpenAPIDefinition为我们所有的Web API设置了顶级定义。 移动到PeopleRestService,我们只需添加@Tag注释,那么,标签我们的API。
@Path( "/people" )
@Tag(name = "people")
public class PeopleRestService {// ...
}
太棒了,到目前为止没有什么复杂的。 最棘手的部分从Web API操作定义开始,因此让我们看一下第一个示例,即获取所有人的操作。
@Produces(MediaType.APPLICATION_JSON)
@GET
@Operation(description = "List all people", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Person.class))),responseCode = "200")}
)
public Collection<Person> getPeople() {// ...
}
相当多的注释,但总的来说,看起来很干净直接。 让我们看一下另一个,即通过其电子邮件地址查找此人的端点。
@Produces(MediaType.APPLICATION_JSON)
@Path("/{email}")
@GET
@Operation(description = "Find person by e-mail", responses = {@ApiResponse(content = @Content(schema = @Schema(implementation = Person.class)), responseCode = "200"),@ApiResponse(responseCode = "404", description = "Person with such e-mail doesn't exists")}
)
public Person findPerson(@Parameter(description = "E-Mail address to lookup for", required = true) @PathParam("email") final String email) {// ...
}
同样,通过电子邮件删除该人的操作看起来几乎是相同的。
@Path("/{email}")
@DELETE
@Operation(description = "Delete existing person",responses = {@ApiResponse(responseCode = "204",description = "Person has been deleted"),@ApiResponse(responseCode = "404", description = "Person with such e-mail doesn't exists")}
)
public Response deletePerson(@Parameter(description = "E-Mail address to lookup for", required = true ) @PathParam("email") final String email) {// ...
}
太好了,让我们总结一下最后一个可以说是最有趣的端点,它增加了一个新人(使用@FormParam的选择纯粹是为了说明API的不同风格)。
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
@POST
@Operation(description = "Create new person",responses = {@ApiResponse(content = @Content(schema = @Schema(implementation = Person.class), mediaType = MediaType.APPLICATION_JSON),headers = @Header(name = "Location"),responseCode = "201"),@ApiResponse(responseCode = "409", description = "Person with such e-mail already exists")}
)
public Response addPerson(@Context final UriInfo uriInfo,@Parameter(description = "E-Mail", required = true) @FormParam("email") final String email, @Parameter(description = "First Name", required = true) @FormParam("firstName") final String firstName, @Parameter(description = "Last Name", required = true) @FormParam("lastName") final String lastName) {// ...
}
如果您有使用较旧的Swagger规范记录Web API的经验,那么您可能会发现该方法非常熟悉,但更为冗长(或者更确切地说 ,是形式化的)。 这是规范领导和社区所做的巨大工作的结果,以使其尽可能完整和可扩展。
已定义和记录了API,现在该尝试一下了! 不过,缺少的部分是Spring配置,在该配置中我们将初始化并公开我们的JAX-RS Web服务。
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = PeopleRestService.class)
public class AppConfig {@Autowired private PeopleRestService peopleRestService;@Bean(destroyMethod = "destroy")public Server jaxRsServer(Bus bus) {final JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();factory.setApplication(new JaxRsApiApplication());factory.setServiceBean(peopleRestService);factory.setProvider(new JacksonJsonProvider());factory.setFeatures(Arrays.asList(new OpenApiFeature()));factory.setBus(bus);factory.setAddress("/");return factory.create();}@Beanpublic ServletRegistrationBean cxfServlet() {final ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new CXFServlet(), "/api/*");servletRegistrationBean.setLoadOnStartup(1);return servletRegistrationBean;}
}
OpenApiFeature是这里的关键要素,它负责所有集成和自省。 Spring Boot应用程序是完成图片的最后一步。
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(AppConfig.class, args);}
}
让我们立即构建并运行它:
mvn clean package
java -jar target/jax-rs-2.1-openapi-0.0.1-SNAPSHOT.jar
启动应用程序后,我们的Web API的OpenAPI 3.0.0规范应处于活动状态,并可以JSON格式用于以下位置:
http://localhost:8080/api/openapi.json
或使用YAML格式:
http://localhost:8080/api/openapi.json
探索并使用我们的Web API会很棒吗? 由于我们包含了Swagger UI依赖关系,因此不必理会,只需导航到http:// localhost:8080 / api / api-docs?url = / api / openapi.json :
特别要注意的是,小图标Swagger UI会与您的API版本一起放置,以暗示其符合OpenAPI 3.0.0规范。
这里只需要注意,使用Spring Boot没有什么特别的。 如果您在OSGi容器中使用Apache CXF (例如,例如Apache Karaf ),则还可以与OpenAPI 3.0.0集成(如果您对此主题感兴趣,请查阅官方文档和示例 )。
一切看起来都很简单,但是如何从Swagger规范的较旧版本迁移到OpenAPI 3.0.0呢? Apache CXF具有强大的功能, 可以即时转换较旧的规范,但总的来说, OpenApi.Tools门户是评估选项的正确位置。
您应该迁移到OpenAPI 3.0.0吗? 老实说,我相信您应该,至少应该尝试进行试验,但是请注意,该工具还不够成熟,请期待一些障碍(您可以通过提供补丁来克服这些障碍) )。 但无疑,前程似锦!
完整的项目资源可在Github上找到 。
翻译自: https://www.javacodegeeks.com/2018/05/moving-with-the-times-towards-openapi-v3-0-0-adoption-in-jax-rs-apis.html
与时俱进:在JAX-RS API中采用OpenAPI v3.0.0相关推荐
- input发送a.jax_与时俱进:在JAX-RS API中采用OpenAPI v3.0.0
input发送a.jax 看到时间流逝如此之快,真是太恐怖了! OpenAPI规范3.0.0是对Swagger规范的重大改进,大部分已于一年前发布,但工具赶上了一段时间. 但是,随着最近Swagger ...
- 在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务
在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务 https://procodeguide.com/programming/polly-in-aspnet-core ...
- jax rs mysql_liferay7-rest开发JAX-RS规范详解
简介 JAX-RS (JSR-311) 是为 Java EE 环境下的 RESTful 服务能力提供的一种规范.它能提供对传统的基于 SOAP 的 Web 服务的一种可行替代. 在本文中,了解 JAX ...
- Android2.2 API 中文文档系列(7) —— ImageButton
前言 第七篇关于ImageButton的翻译在翻译工具帮助下独立完成,加了一些自己的理解甚至截图,水平有限,欢迎指正.欢迎更多译者一起参与Android API 的中文翻译行动!我的邮箱over140 ...
- 【译】为什么我们在 API 中使用 GraphQL
本文是对Why we used GraphQL for our API的翻译,如有侵权等其他问题,请联系笔者删除. 最近在 Mavel 我们发布了 Platform API,我们想利用整合的力量,将这 ...
- 【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie
5.5 HTTP Cookies in ASP.NET Web API 5.5 ASP.NET Web API中的HTTP Cookie 本文引自:http://www.asp.net/web-api ...
- ASP.NET Web API中的Controller
虽然通过Visual Studio向导在ASP.NET Web API项目中创建的 Controller类型默认派生与抽象类型ApiController,但是ASP.NET Web API框架本身只要 ...
- 监控系统简介(二):使用 App Metrics 在 ASP.NET Web API 中记录指标
回顾 在<监控系统简介:使用 Prometheus 与 Grafana>一文中,我们了解了什么是监控系统,Prometheus 这一监控工具及它提供的数据类型.PromQL 以及 Graf ...
- json api_JSON模式在构建和部署API中的作用
json api 什么是JSON模式 ? 它提供了一种描述任何JSON值的结构和属性的彻底方法. 在记录对任何JSON API的请求和响应时,它非常有用. 本文将探讨其在API的软件开发周期中的作用. ...
最新文章
- Java面试官:给Java面试者的八点建议
- 谷歌全方位自曝Waymo无人车技术方案 | 42页报告要点解读+下载
- 牛客网暑期ACM多校训练营(第一场)
- v-if 的区别v-show
- Linux启动管理:主引导目录(MBR)结构及作用详解
- 《简明 PHP 教程》03 第一步
- AngularJS判断checkbox/复选框是否选中并实时显示
- windows10环境下node js版本快速升级
- 实战MongoDB-Replication之Master-Slave
- could not extract ResultSet/could not execute statement
- 必须安装三星系列android系统智能手机usb驱动程序,三星安卓4.0怎么刷机 三星安卓4.0刷机教程...
- 【python】习题 1-4周
- it企业实习_IT公司实习报告总结
- 简单一招能让你的浏览器下载速度提升几十倍,从此弃用IDM等下载器
- mysql 部分汉字乱码_一次mysql部分汉字乱码解决过程
- android 键编译,Android 音视频学习系列 (四) 一键编译 32/64 位 FFmpeg 4.2.2
- 2074:【21CSPJ普及组】分糖果(candy)
- 如何与其他用户共享SkyBell HD访问
- [数学基础知识] Cramér‘s V 相关系数和Python算法实现
- 减肥瘦不下来的三个关键
热门文章
- MongoDB嵌套数组,多维数组查询
- 深入浅出讲解语言模型
- Spring Cloud 升级最新 Finchley 版本,踩了所有的坑
- 使用Servlet上传多张图片——Dao层(BaseDao.java)
- admiration音标是什么_英语admiration的意思解释|读音发音|相关词语_英语词典_词林在线词典...
- java开发可以转什么软件有哪些_转行开发软件Java编程必须会什么
- 外部访问docker容器(docker run -p/-P 指令) docker run -d -p 5000:5000 {hostPort:containerPort(映射所有接口地}
- 计算字典的个数_[LeetCode] 440. 字典序的第K小数字
- taro 缺点_Taro小程序富文本解析4种方法
- thinking-in-java(14)类型信息