Swagger UI未显示示例值和模型

huangapple go评论134阅读模式
英文:

<Spring Boot / Springfox> Swagger UI not showing example value and model

问题

I was generating Swagger API specification from Spring Boot REST controllers using Springfox.

我正在使用Springfox从Spring Boot REST控制器生成Swagger API规范。

I noticed an issue where the example value/model could not be shown for response.

我注意到一个问题,响应中的示例值/模型无法显示。

As an investigation, I checked the JSON API doc at http://localhost:8080/v2/api-docs , and converted it to YMAL at https://editor.swagger.io/ , which it could not show the example value/model as well. This seems to caused by the schema is not referring to the model object ("Car" here) correctly.

作为一项调查,我检查了http://localhost:8080/v2/api-docs上的JSON API文档,并将其转换为YMAL格式https://editor.swagger.io/,但它也无法显示示例值/模型。这似乎是由于模式未正确引用模型对象(这里是"Car")。

By specifying response = "Object.class", shouldn't the Swagger UI populate the example value/model accordingly?

通过指定response = "Object.class",Swagger UI不应该相应地填充示例值/模型吗?

Welcome for any advice, and please kindly correct if I have any misconfigurations/misconceptions, thank you very much.

欢迎提供任何建议,如果我有任何配置错误/误解,请友好地指正,非常感谢。

REST controller and the annotations:

REST控制器和注解:

@GetMapping(path = "/car")
@ApiOperation(value = "Get car by color.", response = Car.class)
@ApiParam(value = "Color of the car.", required = true)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK.", response = Car.class),
@ApiResponse(code = 400, message = "Invalid color provided."),
@ApiResponse(code = 404, message = "Car not found.") })
public ResponseEntity getCarByColor(@RequestParam String color) {
return ResponseEntity.ok(testService.getCarByColor(color));
}

Model:

模型:

package com.example.demo.model;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@ApiModel(value = "Car", description = "The model for car")
@Data
public class Car {
@ApiModelProperty(notes = "Car ID.", example = "12345", required = false, position = 0)
private Long id;

@ApiModelProperty(notes = "Car name.", example = "Suzuki Swift 2020", required = true, position = 1)
@NotNull
@Max(value = 30, message = "Name can only have a maximum length of 30")
private String name;

@ApiModelProperty(notes = "Car color.", example = "blue", required = true, position = 2)
@NotNull
@Max(value = 30, message = "Color can only have a maximum length of 30")
@Pattern(regexp = "^(blue|yellow)$", message = "Only blue or yellow color is allowed.")
private String color;

public Car(Long id, String name, String color) {
    this.id = id;
    this.name = name;
    this.color = color;
}

}

Swagger UI:

Swagger UI:

Swagger UI未显示示例值和模型

Springfox dependency in pom.xml:

pom.xml中的Springfox依赖:


io.springfox
springfox-boot-starter
3.0.0

<UPDATE (31 Jul 2020)>

Made the following changes to use OAS3.0 specification and annotations, but still have issue. It also gives an error in Swagger UI.

进行以下更改以使用OAS3.0规范和注解,但仍然存在问题。Swagger UI也报错。

REST controller and the annotations:

REST控制器和注解:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;

...

@GetMapping(path = "/car", produces = "application/json")
@Operation(summary = "Get car by color.", responses = {
@ApiResponse(responseCode = "200", description = "OK.", content = {
@Content(mediaType = "application/json", schema = @Schema(type = "object", implementation = Car.class)) }) })
public ResponseEntity getCarByColor(@RequestParam String color) {
return ResponseEntity.ok(testService.getCarByColor(color));
}

Model:

模型:

package com.example.demo.model;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@ApiModel(value = "Car", description = "The model for car")
@Schema
@Data
public class Car {
@ApiModelProperty(notes = "Car ID.", example = "12345", required = false, position = 0)
private Long id;

@ApiModelProperty(notes = "Car name.", example = "Suzuki Swift 2020", required = true, position = 1)
@NotNull
@Max(value = 30, message = "Name can only have a maximum length of 30")
private String name;

@ApiModelProperty(notes = "Car color.", example = "blue", required = true, position = 2)
@NotNull
@Max(value = 30, message = "Color can only have a maximum length of 30")
@Pattern(regexp = "^(blue|yellow)$", message = "Only blue or yellow color is allowed.")
private String color;

public Car(Long id, String name, String color) {
    this.id = id;
    this.name = name;
    this.color = color;
}

}

Swagger UI:

Swagger UI:

Swagger UI未显示示例值和模型

Swagger UI未显示示例值和模型

英文:

I was generating Swagger API specification from Spring Boot REST controllers using Springfox.

I noticed an issue where the example value/model could not be shown for response.

As an investigation, I checked the JSON API doc at http://localhost:8080/v2/api-docs ,
and converted it to YMAL at https://editor.swagger.io/ , which it could not show the example value/model as well.
This seems to caused by the schema is not referring to the model object ("Car" here) correctly.

Swagger UI未显示示例值和模型

Swagger UI未显示示例值和模型

But from the API documentation of Swagger (https://docs.swagger.io/swagger-core/v1.5.0/apidocs/io/swagger/annotations/ApiResponse.html#response()), it says that the "response" attribute of the annotation @ApiResponse should correspond to the "schema" field of the specification.

Swagger UI未显示示例值和模型

By specifying response = "Object.class", shouldn't the Swagger UI populate the example value/model accordingly?

Welcome for any advice, and please kindly correct if I have any misconfigurations/misconceptions, thank you very much.

<br/>
REST controller and the annotations:

@GetMapping(path = &quot;/car&quot;)
@ApiOperation(value = &quot;Get car by color.&quot;, response = Car.class)
@ApiParam(value = &quot;Color of the car.&quot;, required = true)
@ApiResponses(value = { @ApiResponse(code = 200, message = &quot;OK.&quot;, response = Car.class),
		@ApiResponse(code = 400, message = &quot;Invalid color provided.&quot;),
		@ApiResponse(code = 404, message = &quot;Car not found.&quot;) })
public ResponseEntity&lt;Object&gt; getCarByColor(@RequestParam String color) {
	return ResponseEntity.ok(testService.getCarByColor(color));
}

Model:

package com.example.demo.model;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@ApiModel(value = &quot;Car&quot;, description = &quot;The model for car&quot;)
@Data
public class Car {
    @ApiModelProperty(notes = &quot;Car ID.&quot;, example = &quot;12345&quot;, required = false, position = 0)
    private Long id;

    @ApiModelProperty(notes = &quot;Car name.&quot;, example = &quot;Suzuki Swift 2020&quot;, required = true, position = 1)
    @NotNull
    @Max(value = 30, message = &quot;Name can only have a maximum length of 30&quot;)
    private String name;

    @ApiModelProperty(notes = &quot;Car color.&quot;, example = &quot;blue&quot;, required = true, position = 2)
    @NotNull
    @Max(value = 30, message = &quot;Color can only have a maximum length of 30&quot;)
    @Pattern(regexp = &quot;^(blue|yellow)$&quot;, message = &quot;Only blue or yellow color is allowed.&quot;)
    private String color;

    public Car(Long id, String name, String color) {
        this.id = id;
        this.name = name;
        this.color = color;
    }
}

Swagger UI:

Swagger UI未显示示例值和模型

Springfox dependency in pom.xml:

    &lt;dependency&gt;
		&lt;groupId&gt;io.springfox&lt;/groupId&gt;
		&lt;artifactId&gt;springfox-boot-starter&lt;/artifactId&gt;
		&lt;version&gt;3.0.0&lt;/version&gt;
	&lt;/dependency&gt;

<br/>
<br/>
<br/>
<br/>
<br/>

<UPDATE (31 Jul 2020)>

Made the following changes to use OAS3.0 specification and annotations, but still have issue. It also gives an error in Swagger UI.

REST controller and the annotations:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;

...
......

@GetMapping(path = &quot;/car&quot;, produces = &quot;application/json&quot;)
@Operation(summary = &quot;Get car by color.&quot;, responses = {
		@ApiResponse(responseCode = &quot;200&quot;, description = &quot;OK.&quot;, content = {
				@Content(mediaType = &quot;application/json&quot;, schema = @Schema(type = &quot;object&quot;, implementation = Car.class)) }) })
public ResponseEntity&lt;Object&gt; getCarByColor(@RequestParam String color) {
	return ResponseEntity.ok(testService.getCarByColor(color));
}

Model:

package com.example.demo.model;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@ApiModel(value = &quot;Car&quot;, description = &quot;The model for car&quot;)
@Schema
@Data
public class Car {
	@ApiModelProperty(notes = &quot;Car ID.&quot;, example = &quot;12345&quot;, required = false, position = 0)
	private Long id;

	@ApiModelProperty(notes = &quot;Car name.&quot;, example = &quot;Suzuki Swift 2020&quot;, required = true, position = 1)
	@NotNull
	@Max(value = 30, message = &quot;Name can only have a maximum length of 30&quot;)
	private String name;

	@ApiModelProperty(notes = &quot;Car color.&quot;, example = &quot;blue&quot;, required = true, position = 2)
	@NotNull
	@Max(value = 30, message = &quot;Color can only have a maximum length of 30&quot;)
	@Pattern(regexp = &quot;^(blue|yellow)$&quot;, message = &quot;Only blue or yellow color is allowed.&quot;)
	private String color;

	public Car(Long id, String name, String color) {
		this.id = id;
		this.name = name;
		this.color = color;
	}
}

Swagger UI:

Swagger UI未显示示例值和模型

Swagger UI未显示示例值和模型

答案1

得分: 3

你可以使用V2模型来覆盖V3模型。只需在你的application.properties中添加一个属性,你的@ApiResponse注解就应该正常工作。

springfox.documentation.swagger.use-model-v3=false

确保使用旧版本的@ApiResponses@ApiResponse注解。
这个问题已经记录在https://github.com/springfox/springfox/issues/3503。

英文:

You can override V3 models with V2 models. Just add a property in your application.properties and your @ApiResponse annotation should work properly.

springfox.documentation.swagger.use-model-v3=false

Make sure to use older @ApiResponses and @ApiResponse annotations.
This issue has been documented an https://github.com/springfox/springfox/issues/3503

答案2

得分: 2

以下是您要翻译的内容:

在使用 springdoc-openapi-ui(版本 >= 1.5.0)的情况下,这是我的工作示例,用于在 SwaggerUI 的请求和响应部分显示 JSON 对象的示例数据。
希望它可以适用于您的情况,只需进行少量更改。

@Operation(summary = "发送一些 JSON")
@ApiResponses(value = {
    @ApiResponse(
        responseCode = "200",
        description = "成功:我们的操作已完成",
        content = @Content(mediaType = "application/json",
        schema = @Schema(
            type = "SampleHttpResponseDto",
            example = "{\"status\":\"OK\",\"message\":\"sample OK answer\"}")))})
@PostMapping(value = "/resource", consumes = MediaType.APPLICATION_JSON_VALUE)
public SampleHttpResponseDto postRequest(
    @Parameter(
        name ="json",
        schema = @Schema(
            description = "模型的附加描述",
            type = "string",
            example = "{\"status\":\"OK\",\"message\":\"message body\"}"))
    @RequestBody Map<String, Object> request
) {
  return new SampleHttpResponseDto(request.property1, request.property2);
}

Gist 链接:https://gist.github.com/antukhov/7dece86c6d16cc81bb6f83f47ffc0c8d

SwaggerUI 将会看起来像这样

英文:

In the case of using the springdoc-openapi-ui (>=1.5.0) here is my working sample to show example data in the request and response sections of SwaggerUI if it's the JSON object.
Hopefully, it would fit your case with small changes too.

@Operation(summary = &quot;Send some JSON&quot;)
@ApiResponses(value = {
    @ApiResponse(
        responseCode = &quot;200&quot;,
        description = &quot;Success: our action has been completed&quot;,
        content = @Content(mediaType = &quot;application/json&quot;,
        schema = @Schema(
            type = &quot;SampleHttpResponseDto&quot;,
            example = &quot;{\&quot;status\&quot;:\&quot;OK\&quot;,\&quot;message\&quot;:\&quot;sample OK answer\&quot;}&quot;)))})
@PostMapping(value = &quot;/resource&quot;, consumes = MediaType.APPLICATION_JSON_VALUE)
public SampleHttpResponseDto postRequest(
    @Parameter(
        name =&quot;json&quot;,
        schema = @Schema(
            description = &quot;additional description of the model&quot;,
            type = &quot;string&quot;,
            example = &quot;{\&quot;status\&quot;:\&quot;OK\&quot;,\&quot;message\&quot;:\&quot;message body\&quot;}&quot;))
    @RequestBody Map&lt;String, Object&gt; request
) {
  return new SampleHttpResponseDto(request.propert1, request.propert2);
}

Gist: https://gist.github.com/antukhov/7dece86c6d16cc81bb6f83f47ffc0c8d

SwaggerUI will look like this

答案3

得分: 0

使用swagger-2注解对我有用,通过将produces=&#39;application/json&#39;添加到@GetMapping或任何@RequestMapping

英文:

Using swagger-2 annotation worked for me by adding produces=&#39;application/json&#39; to @GetMapping or any @RequestMapping.

huangapple
  • 本文由 发表于 2020年7月30日 16:41:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63169386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定

  • 开发者交流平台

    本页二维码