Ich erstelle eine API REST mit Spring Boot und erstelle automatisch die Swagger-Dokumentation in Controllern mit Swagger-Codegen. Ich kann jedoch keine Beschreibung und kein Beispiel für einen Parameter vom Typ String in festlegen eine POST Anfrage. Hier ist mein Code:
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;
}
Die Beispieleigenschaft von @ApiParam wurde von mir manuell eingefügt, da der Codegen diesen Teil des yaml ignorierte (Das ist eine andere Frage: Warum ignoriert der Editor den Beispielteil?). Hier ist ein Teil des Yamls:
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
}
Und schließlich zeigt Swagger Folgendes:
Schließlich sind die in build.gradle verwendeten Abhängigkeiten die folgenden:
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
Die Frage lautet also: Weiß jemand, wie ich die Beschreibung und ein Beispiel eines Körperparameters mithilfe von Prahleranmerkungen festlegen kann?
[~ # ~] edit [~ # ~]
Ich habe es geschafft, die Beschreibung mit @ApiImplicitParam anstelle von @ApiParam zu ändern, aber es fehlt noch ein Beispiel:
@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}")}))})
Ich habe ein ähnliches Problem beim Generieren von Beispielen für Körperobjekte - Annotation @Example
Und @ExampleProperty
Funktionieren in swagger 1.5.x einfach nicht ohne Grund. (Ich benutze 1.5.16)
Meine aktuelle Lösung ist:
Verwenden Sie @ApiParam(example="...")
für Nichtkörperobjekte, z.
public void post(@PathParam("userId") @ApiParam(value = "userId", example = "4100003") Integer userId) {}
für body Objekte werden neue Klassen erstellt und Felder mit @ApiModelProperty(value = " ", example = " ")
beschriftet, z.
@ApiModel(subTypes = {BalanceUpdate.class, UserMessage.class})
class PushRequest {
@ApiModelProperty(value = "status", example = "Push")
private final String status;;
}
Eigentlich das Java doc für die example
-Eigenschaft des @ApiParam
annotation gibt an, dass dies ausschließlich für Nicht-Body-Parameter verwendet werden soll. Dabei kann die Eigenschaft examples
für Körperparameter verwendet werden.
Ich habe diese Anmerkung getestet
@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}"
)
)
)
was dazu führte, dass für die entsprechende Methode folgende Prahlerei generiert wurde:
/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}"
Dieser Wert scheint jedoch nicht von swagger-ui erfasst zu werden. Ich habe Version 2.2.10 und die neueste Version 3.17.4 ausprobiert, aber in keiner der Versionen wurde x-examples
Eigentum des Prahlers.
Es gibt einige Referenzen für x-example
(der für Nicht-Körper-Parameter verwendete) im Code von swagger-ui , aber keine Übereinstimmung für x-examples
. Das heißt, dies scheint momentan nicht von swagger-ui unterstützt zu werden.
Wenn Sie diese Beispielwerte wirklich benötigen, besteht Ihre beste Möglichkeit derzeit darin, die Signatur Ihrer Methode zu ändern und einen dedizierten Domänentyp für den body-Parameter zu verwenden. Wie bereits in den Kommentaren erwähnt, erkennt swagger automatisch die Struktur des Domain-Typs und gibt einige nützliche Informationen in swagger-ui aus:
Haben Sie folgendes versucht?
@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}")
Einen schönen Tag noch
Wenn Sie swagger 2.9.2 verwenden, funktionieren die Beispiele dort nicht. Diese Anmerkungen werden ignoriert
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;
}
Versuchen Sie es mit swagger 3.0.0-Snapshot. Sie müssen Maven-Abhängigkeiten wie folgt ändern:
<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>
und ändern Sie die Anmerkung in Ihrer Swagger-Konfigurationsdatei in: @ EnableSwagger2WebMvc