Skip to main content

dawdler-client-api-generator

Module Introduction​

A tool that generates an OpenAPI 3.1 JSON document compatible with swagger-ui from Java source code and its Javadoc. It is non-invasive to the source code, easy to get started with, generates efficiently and is very convenient to use.

1. Adding the dependency in pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-client-api-generator</artifactId>

2. dawdler-web-api.yml configuration file reference​

Example:

version: 1.0
title: "Order web service"
description: "Order web service documentation"
contact:
name: "jackson.song"
email: "suxuan696@gmail.com"
url: "https://github.com/srchen1987"
openApi: "3.1.0"
servers:
- url: http://localhost:8085
description: Local server
- url: https://api.example.com
description: Production server
- url: https://staging.example.com
description: Staging server
scanPath:
- "/home/srchen/github/simple-single-user-web-api/src/main/java/club/dawdler/user"
- "/home/srchen/github/dawdler-series-jdk25/dawdler-series/dawdler/dawdler-load-bean/src/main/java"
outPath: "/home/srchen/github/api-demo/upload-api.json"

Description:

NameDescription
versionVersion number
titleTitle
descriptionDescription
contactContact information
openApiopenApi version number
serversAPI addresses, e.g. 192.168.1.55:8080
scanPathScan paths for Controllers or entity objects (array structure)
outPathPath of the generated json output

3. Usage​

3.1 Basic configuration​

Configure by referring to the dawdler-web-api.yml file and make sure scanPath is set correctly.

3.2 Requirements​

scanPath must be configured correctly, and there must be Controllers under those paths (only classes annotated with @Controller take effect).

Method return values must be annotated with @ResponseBody; types other than the primitive types, String or BigDecimal also need to be within scanPath to take effect.

Objects annotated with @RequestBody in method parameters need to be within scanPath to take effect.

Returned objects need the @ResponseBody annotation; unsupported types (such as Map) are not parsed.

3.3 Generating the api file​

java -jar dawdler-client-api-generator-xxx-RELEASES.jar /home/srchen/github/api-demo/dawdler-web-api.yml

After running, demo-api.json is generated (at the path configured by outPath).

3.4 Starting swagger-ui​

Pull the docker image

docker pull docker.swagger.io/swaggerapi/swagger-ui

Start it

docker run -d -p 80:8080 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/demo-api.json -e DEFAULT_RESPONSES_EXPAND_DEPTH=10 -e DEFAULT_MODELS_EXPAND_DEPTH=10 -e DEFAULT_MODEL_EXPAND_DEPTH=10 -v {directory containing api-json}:/foo docker.swagger.io/swaggerapi/swagger-ui

Then visit http://localhost/swagger to use it.

4. Supported JavaDoc tags / annotations / objects​

4.1 JavaDoc tags​

  1. The description of a class or method; can be placed on the class or on the method (standard Javadoc method comments are also supported).

  2. @param provides the comment for a method parameter; only supported on methods.

If the comment contains @param userId The user ID, the parameter userId in the method signature is documented with that name.

For example:

/**
* @author jackson.song
* Query a user by user ID
* @param userId The user ID
*
*/
@RequestMapping(value = "/user/get",method = RequestMethod.GET)
@ResponseBody
public User get(String userId){
return null;
}

4.2 dawdler-client-plug annotations​

  1. @Controller marks a class as a Controller; only classes with this marker are scanned and documented. Used on classes.

  2. @RequestMapping sets the path of the request API; only APIs with this marker are scanned and documented. Supported on classes and methods.

  3. @RequestParam specifies the name of a request parameter; can be used together with @param for the comment. Note that the value in RequestParam must match the value of @param to take effect.

  4. @PathVariable obtains a path variable; used in the parameter list of a method, and can be used together with @param for the comment.

  5. @RequestHeader obtains a value from the header; used in the parameter list of a method, and can be used together with @param for the comment.

  6. @RequestBody marks an object passed in as the http body.

  7. @ResponseBody marks the returned object.

4.3 Object types supported in method parameter lists (types supported by dawdler-client-plug)​

  1. UploadFile The object used for file uploads; can be used together with @param for the comment.

  2. The 8 Java primitive types Used to obtain http request parameters; can be used together with @param for the comment.

  3. String type Used to obtain http request parameters; can be used together with @param for the comment.

  4. BigDecimal Used to obtain http request parameters; can be used together with @param for the comment.

  5. Date, LocalDateTime, LocalDate, LocalTime, ZonedDateTime, OffsetDateTime Used to obtain http request parameters; can be used together with @param for the comment.

  6. Enum Enum types Used to obtain http request parameters; can be used together with @param for the comment.

  7. Custom objects (when marked with @RequestBody an http body is required; without @RequestBody, the properties of the custom object are sent as http param parameters) Comments are only supported as annotations inside the custom object, in the form /comment/. For example:

public class User {
/**
* User ID
*/
private Integer userId;
/**
* User name
*/
private String userName;
/**
* Address
*/
private String address;

public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

5. Supported return types​

  1. The 8 primitive types and arrays thereof

  2. String type and arrays thereof

  3. BigDecimal and arrays thereof

  4. List<type>/Set<type>/Collection<type>/Vector<type>

  5. Custom classes, with generics supported.

6. Demo​

DemoController is an example of a Controller.


package club.dawdler.demo.api.controller;

import java.util.List;

import club.dawdler.clientplug.annotation.Controller;
import club.dawdler.clientplug.annotation.PathVariable;
import club.dawdler.clientplug.annotation.RequestBody;
import club.dawdler.clientplug.annotation.RequestHeader;
import club.dawdler.clientplug.annotation.RequestMapping;
import club.dawdler.clientplug.annotation.RequestMapping.RequestMethod;
import club.dawdler.clientplug.annotation.ResponseBody;
import club.dawdler.clientplug.web.upload.UploadFile;
import club.dawdler.demo.api.BaseResult;
import club.dawdler.demo.api.InnerResult;
import club.dawdler.demo.api.entity.User;
import club.dawdler.demo.api.entity.UserBank;

/**
*
* @ClassName: DemoController
* Demonstration demo
* @author jackson.song
*/
@Controller
public class DemoController {

/**
* Query a user by user ID
* @author jackson.song
* @param userId The user ID
**/

@RequestMapping(value = "/user/get", method = RequestMethod.GET)
@ResponseBody
public User get(String userId) {
return null;
}

/**
* @author jackson.song
* Query a user by user id, antPath style
* @param id The user ID
**/

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
@ResponseBody
public User getUserByUserId(@PathVariable("id") int id) {
return null;
}

/**
* @author jackson.song
* Query a user by user ID and return a composite bean
* @param userId The user ID
*
*/

@RequestMapping(value = "/user/getUserComposite", method = RequestMethod.POST)
@ResponseBody
public BaseResult<InnerResult<InnerResult<User>>, InnerResult<UserBank>> getUserComposite(int userId) {
return null;
}

/**
* @author jackson.song
* Query a user by user ID and return a composite bean; the result is a List structure
* @param userId
* @return
*
*/
@RequestMapping(value = "/user/getUserComposite2", method = RequestMethod.POST)
@ResponseBody
public BaseResult<List<User>, UserBank> getUserComposite2(int userId) {
return null;
}

/**
* @author jackson.song
* Create a user
**/
@RequestMapping(value = "/user/create", method = RequestMethod.POST)
@ResponseBody
public boolean create(@RequestBody User user) {
return false;
}

/**
* @author jackson.song
* Test obtaining information from the header
* @param token The request header value
*
**/

@RequestMapping(value = "/head/test", method = RequestMethod.GET)
public String headTest(@RequestHeader("token") String token) {
return token;
}

/**
* @author jackson.song
* Test file upload
* @param id Business id
* @param file File
* @return
*
**/

@RequestMapping(value = "/testFileUpload", method = RequestMethod.POST)
@ResponseBody
public boolean testFileUpload(Integer id, UploadFile[] file) {
return false;
}

/**
* @author jackson.song
* Generate the corresponding Http param parameters from the properties of the User entity object
*
*/
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
@ResponseBody
public User createUser(User user) {
return null;
}

}

User entity class

package club.dawdler.demo.api.entity;

/**
*
* @ClassName: User
*: User entity
* @author jackson.song
*/
public class User {
/**
* User ID
*/
private Integer userId;

/**
* User name
*/
private String userName;

/**
* Address
*/
private String address;

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

UserBank entity class

package club.dawdler.demo.api.entity;

public class UserBank {

/** Bank card ID */
private int cardid;
/** userid */
private int userid;
/** Bank type id */
private int bankid;
/** Account opening bank */
private String openBank;
/** Cardholder name */
private String username;
/** Bank card number */
private String cardNumber;
/** Whether valid, 1 means valid */
private Boolean visible;
/** Creation time */
private int createDate;
/** Creator */
private int creator;

public int getCardid() {
return cardid;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getBankid() {
return bankid;
}
public void setBankid(int bankid) {
this.bankid = bankid;
}
public String getOpenBank() {
return openBank;
}
public void setOpenBank(String openBank) {
this.openBank = openBank;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public int getCreateDate() {
return createDate;
}
public void setCreateDate(int createDate) {
this.createDate = createDate;
}
public int getCreator() {
return creator;
}
public void setCreator(int creator) {
this.creator = creator;
}

}

BaseResult base result class

package club.dawdler.demo.api;

public class BaseResult<T, S> {

private T data;

private S dataS;

/**
* Message
*/
private String message;

/**
* Whether successful
*/
private Boolean success;

public S getDataS() {
return dataS;
}

public void setDataS(S dataS) {
this.dataS = dataS;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Boolean getSuccess() {
return success;
}

public void setSuccess(Boolean success) {
this.success = success;
}

}

InnerResult A temporary test class created to test multi-level generics


package club.dawdler.demo.api;

import java.util.List;

import club.dawdler.demo.api.entity.UserBank;

public class InnerResult<F> {
private F datas;
/**
* Status
*/
private int status;
private List<UserBank> userBanks;

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public F getDatas() {
return datas;
}

public void setDatas(F datas) {
this.datas = datas;
}

public List<UserBank> getUserBanks() {
return userBanks;
}

public void setUserBanks(List<UserBank> userBanks) {
this.userBanks = userBanks;
}
}