Как установить описание и пример в Swagger с помощью аннотаций Swagger?
Я создаю REST Api, используя Spring boot, и автоматически генерирую документацию swagger в контроллерах, используя swagger codegen. Однако я не могу установить описание и пример для параметра типа String в запросе POST. Вот ми код:
import io.swagger.annotations.*;
@Api(value = "transaction", tags = {"transaction"})
@FunctionalInterface
public interface ITransactionsApi {
@ApiOperation(value = "Places a new transaction on the system.", notes = "Creates a new transaction in the system. See the schema of the Transaction parameter for more information ", tags={ "transaction", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Another transaction with the same messageId already exists in the system. No transaction was created."),
@ApiResponse(code = 201, message = "The transaction has been correctly created in the system"),
@ApiResponse(code = 400, message = "The transaction schema is invalid and therefore the transaction has not been created.", response = String.class),
@ApiResponse(code = 415, message = "The content type is unsupported"),
@ApiResponse(code = 500, message = "An unexpected error has occurred. The error has been logged and is being investigated.") })
@RequestMapping(value = "/transaction",
produces = { "text/plain" },
consumes = { "application/json" },
method = RequestMethod.POST)
ResponseEntity<Void> createTransaction(
@ApiParam(
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required." ,
example = "{foo: whatever, bar: whatever2}")
@Valid @RequestBody String kambiTransaction) throws InvalidTransactionException;
}
Свойство примера @ApiParam было вставлено мной вручную, потому что codegen игнорировал эту часть yaml (Это другой вопрос: почему редактор игнорирует часть примера?). Вот часть Ямла:
paths:
/transaction:
post:
tags:
- transaction
summary: Place a new transaction on the system.
description: >
Creates a new transaction in the system. See the schema of the Transaction parameter
for more information
operationId: createTransaction
parameters:
- $ref: '#/parameters/transaction'
consumes:
- application/json
produces:
- text/plain
responses:
'200':
description: Another transaction with the same messageId already exists in the system. No transaction was created.
'201':
description: The transaction has been correctly created in the system
'400':
description: The transaction schema is invalid and therefore the transaction has not been created.
schema:
type: string
description: error message explaining why the request is a bad request.
'415':
description: The content type is unsupported
'500':
$ref: '#/responses/Standard500ErrorResponse'
parameters:
transaction:
name: kambiTransaction
in: body
required: true
description: A JSON value representing a kambi transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.
schema:
type: string
example:
{
foo*: whatever,
bar: whatever2
}
И, наконец, вот что показывает чванство:
![enter image description here]()
Наконец, зависимости, используемые в build.gradle, следующие:
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
Итак, вопрос: кто-нибудь знает, как я могу установить описание и пример параметра тела, используя аннотации чванства?
РЕДАКТИРОВАТЬ
Мне удалось изменить описание, используя @ApiImplicitParam вместо @ApiParam, но пример по-прежнему отсутствует:
@ApiImplicitParams({
@ApiImplicitParam(
name = "kambiTransaction",
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with * means that they are required. See the schema of KambiTransaction for more information.",
required = true,
dataType = "String",
paramType = "body",
examples = @Example(value = {@ExampleProperty(mediaType = "application/json", value = "{foo: whatever, bar: whatever2}")}))})
Ответы
Ответ 1
У меня похожая проблема с генерацией примеров для объектов тела - аннотации @Example
и @ExampleProperty
просто не работают без причины в swagger 1.5.x. (Я использую 1.5.16)
Мое текущее решение:
используйте @ApiParam(example="...")
для объектов, не связанных с телом, например:
public void post(@PathParam("userId") @ApiParam(value = "userId", example = "4100003") Integer userId) {}
для объектов тела создайте новый класс и аннотируйте поля с помощью @ApiModelProperty(value = " ", example = " ")
, например:
@ApiModel(subTypes = {BalanceUpdate.class, UserMessage.class})
class PushRequest {
@ApiModelProperty(value = "status", example = "push")
private final String status;;
}
Ответ 2
На самом деле документ Java для example
свойства аннотации @ApiParam
утверждает, что он должен использоваться исключительно для параметров, не связанных с телом. Где свойство examples
может быть использовано для параметров тела.
Я проверил эту аннотацию
@ApiParam(
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
examples = @Example(value =
@ExampleProperty(
mediaType = MediaType.APPLICATION_JSON,
value = "{foo: whatever, bar: whatever2}"
)
)
)
что привело к созданию следующего чванства для соответствующего метода:
/transaction:
post:
...
parameters:
...
- in: "body"
name: "body"
description: "A JSON value representing a transaction. An example of the expected\
\ schema can be found down here. The fields marked with an * means that\
\ they are required."
required: false
schema:
type: "string"
x-examples:
application/json: "{foo: whatever, bar: whatever2}"
Однако это значение, похоже, не воспринимается Swagger-UI. Я пробовал версию 2.2.10 и последнюю версию 3.17.4, но ни одна из версий не использовала свойство x-examples
из swagger.
В коде swagger-ui есть некоторые ссылки на x-example
(тот, который используется для параметров, не связанных с телом), но нет совпадения для x-examples
. То есть, на данный момент это не поддерживается swagger-ui.
Если вам действительно нужно, чтобы значения этого примера присутствовали, вам лучше всего изменить подпись метода и использовать выделенный тип домена для параметра body. Как уже отмечалось в комментариях, swagger автоматически определит структуру типа домена и выведет приятную информацию в swagger-ui:
![Swagger-UI 2.2.10 with domain type info]()
Ответ 3
Вы пробовали следующее?
@ApiModelProperty(
value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
example = "{foo: whatever, bar: whatever2}")
Хороший день
Ответ 4
Если вы используете Swagger 2.9.2, примеры там не работают. Эти аннотации игнорируются
protected Map<String, Response> mapResponseMessages(Set<ResponseMessage> from) {
Map<String, Response> responses = newTreeMap();
for (ResponseMessage responseMessage : from) {
Property responseProperty;
ModelReference modelRef = responseMessage.getResponseModel();
responseProperty = modelRefToProperty(modelRef);
Response response = new Response()
.description(responseMessage.getMessage())
.schema(responseProperty);
**response.setExamples(Maps.<String, Object>newHashMap());**
response.setHeaders(transformEntries(responseMessage.getHeaders(), toPropertyEntry()));
Map<String, Object> extensions = new VendorExtensionsMapper()
.mapExtensions(responseMessage.getVendorExtensions());
response.getVendorExtensions().putAll(extensions);
responses.put(String.valueOf(responseMessage.getCode()), response);
}
return responses;
}
Попробуйте использовать swagger 3.0.0-Snapshot. Вам нужно изменить зависимости maven следующим образом:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-webmvc</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
и измените аннотацию в вашем конфигурационном файле Swagger следующим образом: @EnableSwagger2WebMvc