`
kanpiaoxue
  • 浏览: 1780950 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

swagger生成javaAPI的server&client代码

 
阅读更多

 

 

文章原文:

《Spring Boot: API First Approach》:https://dzone.com/articles/spring-boot-api-first-approach?edition=664392

 

提到的工具:

1、https://editor.swagger.io/

2、https://openapi-generator.tech/

 

 

 

I describe how I created the API definition, then how I created the server and client code from the API definition. Then I will talk about some of the problems I faced.

  · Java Zone · Tutorial
 

 Comment (1)

 
Save
 
 5,120 Views
 
 

In this blog, I take a practical approach to API first design with Open API 3 specification.

Firstly, I describe how I created the API definition, then how I created the server and the client code from the API definition. Then I will talk about some of the problems I faced.

Advantages of API First Approach

As we are adopting microservice-based architectures, API first approach has been gaining some traction. There are quite many advantages to using API first approach and I will discuss a few of them.

Clear Contract Definition

With API first approach, you can create a concrete contract with which you can set clear goals on what will be provided by your application. It also helps to decouple your implementation from the Interface you provide via the API.

Well Documented API

You follow well-structured documentation of the API you are providing and it helps stakeholders to have a clear understanding of the interface you are providing via your APIs in a human-readable format.

Promotes Development in Parallel

This is one of the advantages that I really love is that the producer and consumer of the API can work in parallel once you have the API definition in place. The Consumer can easily create mocks with the already agreed API contract and start their end of the development.

Let’s Get Started!

To start off, I went to https://editor.swagger.io/ and created my API definition. I used the Open API 3 specification to create the API definition. There are many other tools to create your API definition, but I choose this as I was familiar with creating Swagger API documentation in Java. I used this online editor as it provides an auto-complete feature (with ctrl + space) depending on the context you are in. This helped me a lot to create the API definition.

However, I am not a fluent API definition creator, So I learned the way to define the API using the petstore API definition example. 

To get started, I created a very minimal API definition in which I can create an account using a post request.

API Definition Code

Generating Code

With the API definition all set, let’s start with creating the server and client of the API. For this, I created a spring boot application which I created normally via https://start.spring.io. The only dependency I added here was spring-web .

Next, I used the Open API Generator Maven plugin to create the server and the client for me. Let’s see how to do that.

Server-side Code Generation

To create the server-side code from the API definition, I added the Open API generator plugin and provided it with the API definition file. Since I am creating a server based on spring, I provided a generation type spring, So that it knows it can use spring classes to create my server code. There are quite a few server code generators that you can find here. Now, let's look at what the plugin config looks like:

Server Plugin Config

Some of the customization options I used here were, which package name to use to create my API and model classes. There are quite a few other options you can specify. E.g., you can define what your model class names can be pre-appended with and you can find the various other options on their GitHub link.

Now, the code that gets generated from the plugin requires a few more dependencies for it to compile successfully. I exactly found the minimal set I needed and added the following dependencies.

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox-version}</version>
</dependency>
<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>jackson-databind-nullable</artifactId>
    <version>${jackson-databind-nullable}</version>
</dependency>
<dependency>
    <groupId>io.swagger.core.v3</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>${swagger-annotations-version}</version>
</dependency>

 

Now comes the main part, i.e., generating the code. After building the code using mvn clean verify, there were a few classes that got generated.

Generated Classes

In the API package, there were two main interfaces, AccountApi and AccountApiDeligate . The AccountApi interface contains the actual definition of the API using @postmapping annotation and it also contains the required API documentation using spring swagger annotations. Its implementation class is AccountApiController which calls the delegated service.

The important interface for you is the AccountApiDelegate interface. This provides a delegate service pattern, which allows you to provide the implementation of what needs to be handled or done when the API is called. Here you put in your business logic that handles the request. Once you implement the service delegate, you are actually ready to serve requests.

That’s it, you are done with the server-side. Next, the Client.

Client Code Generation

For the client-side code generation, I use the same plugin, but this time with the generator name as java . 

Client Code Generation

I also provide some config properties, Like the library to use for making the rest client. Here I wanted it to use restemplate for making the calls to the server. There are quite a few options you can configure that you can find from their documentation here.

You would also require some more dependencies to help you compile the generated code. 

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>${gson.version}</version>
</dependency>
<dependency>
   <groupId>io.swagger.core.v3</groupId>
   <artifactId>swagger-annotations</artifactId>
   <version>${swagger-annotations-version}</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>${springfox-version}</version>
</dependency>
<dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>okhttp</artifactId>
   <version>${okhttp.version}</version>
</dependency>
<dependency>
   <groupId>com.google.code.findbugs</groupId>
   <artifactId>jsr305</artifactId>
   <version>${jsr305.version}</version>
</dependency>

 

Client Code Dependencies

After the code generation, You can find classes that provide you how to configure the client to talk to the server. It also provides some basic authentication, using bearer token or basic auth.

Now you need to create an instance/bean of the ApiClient . This contains the host config of the server you want to communicate. This is then used in the AccountApi class to help you make requests to the server. To make a request, you would only have to call the API function from the AccountApi class.

There we have it now. You have successfully generated the client code and you can now check the interaction between the client and the server.

Problems I Encountered

There are quite a few bugs in the latest version of the plugin that I was using (5.0.1).

  • For spring generator, there are some unused imports from spring data that get added by the generator while creating the controller. Hence you would have to add spring data dependency, Even if you not using a database with the service. This may not be a big problem, because mostly you would have a database that you connect to with your service. You can check the current open bug here.
  • Usually, you would define the schema for request and response in the components section of the API definition file and then use the reference to these schemas in the API using the $ref: property. This is currently not working as excepted. The way to get around it was to define the inline schema for each request and response. Hence the model names get generated with a prefix Inline* . You can track this bug here.

If you use the older version, i.e, 4.3.1 ; it's free from these bugs and the plugin works well as expected. 

As usual, I have uploaded the code to GitHub. Enjoy!!

 
Topics:
 
JAVA, OPEN API, SPRING BOOT, TUTORIAL
分享到:
评论

相关推荐

    grafana-client-sdk:使用Swagger生成Grafana Restful API的客户端SDK

    grafana-client-sdk 使用Swagger生成Grafana Restful API的客户端SDK。特征资料夹API 具有仪表板架构版本16的仪表板API。 数据源API对于开发人员修改codegen.sh以为您需要的任何语言和框架生成sdk。 修改grafana-...

    spring boot-2.1.16整合swagger-2.9.2 含yml配置文件的代码详解

    Swagger Codegen 是一个代码生成器,用于根据 API 文档生成客户端代码。 Spring Boot 整合 Swagger 要将 Spring Boot 整合 Swagger,需要添加 Swagger 的依赖项并配置 Swagger。下面是一个简单的示例: 首先,...

    WebServiceDemoGH.zip

    Idea会自动生成WSDL(Web Service Description Language)文件,这是SOAP服务的标准描述语言,或者使用Swagger等工具为REST服务生成API文档。 在项目中,可能还包含了客户端调用Web服务的示例代码,这可以帮助...

    基于springboot的设备管理系统+源代码+文档说明

    - 引入swagger文档支持,方便编写API接口文档 **数据权限设计思想** - 管理员管理、角色管理、部门管理,可操作本部门及子部门数据 - 菜单管理、定时任务、参数管理、字典管理、系统日志,没有数据权限 - ...

    springcloud.rar

    6. **SpringBoot-Swagger2**:Swagger2是一个流行的API文档生成工具,它可以自动生成RESTful API的文档和测试界面。`springboot-swagger2`项目可能包含了使用Swagger2注解的RESTful API,方便开发者理解和测试接口。...

    upload-multifile-server:带有RESTful示例的Java服务器上载多文件演示

    标题中的"upload-multifile-server"是一个项目,专注于在Java服务器上实现多文件上传功能,同时结合了RESTful API的设计原则。这个项目提供了一个演示,展示了如何通过RESTful接口接收和处理多个文件的上传请求。 ...

    REST相关jar包

    它包含的核心jar包包括jersey-server、jersey-client、jersey-media-multipart等,分别对应服务器端、客户端和多媒体支持。 3. **Jackson或Gson**:在REST服务中,数据通常以JSON格式进行交换。Jackson和Gson是两个...

    jersey的开发包

    10. **文档生成**:通过Swagger等工具,Jersey可以生成REST服务的API文档,方便客户端开发者理解和使用。 在“jersey的开发包”中,可能包含以下文件和目录: - `jersey-core`:核心库,包含JAX-RS标准注解和基本...

    单点登录源码

    | ├── zheng-upms-dao -- 代码生成模块,无需开发 | ├── zheng-upms-client -- 集成upms依赖包,提供单点认证、授权、统一会话管理 | ├── zheng-upms-rpc-api -- rpc接口包 | ├── zheng-upms-rpc-...

    openapi-codegen:OpenAPI 3.0 CodeGen加上Node.js减去Java和表情符号

    OpenAPI代码生成 OpenAPI文档的基于Node.js的代码生成。 这个项目最初是24小时的黑客马拉松。 本地模型适配器代码完全是原始代码,并已根据现有文档和模板使用情况进行了反向工程。 工作正在进行中 本机支持...

    MCloud - OAuth2 认证中心

    `mcloud-oauth-server` 基于**Spring OAuth2**,实现了**OAuth2**认证服务器以及资源服务器,并以 **Restful API** 的方式提供了**OAuth** 客户端以及用户的管理功能。 项目中主要使用了以下技术: - **Java8** - *...

Global site tag (gtag.js) - Google Analytics