|
3 | 3 | import com.fasterxml.jackson.databind.node.ObjectNode;
|
4 | 4 | import com.google.inject.Singleton;
|
5 | 5 | import io.swagger.v3.core.util.Json31;
|
| 6 | +import io.swagger.v3.core.util.Yaml31; |
6 | 7 | import io.swagger.v3.oas.annotations.Operation;
|
| 8 | +import io.swagger.v3.oas.annotations.Parameter; |
| 9 | +import io.swagger.v3.oas.annotations.enums.ParameterIn; |
7 | 10 | import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
8 | 11 | import io.swagger.v3.oas.models.OpenAPI;
|
9 | 12 | import net.codestory.http.annotations.Get;
|
10 | 13 | import net.codestory.http.annotations.Prefix;
|
| 14 | +import net.codestory.http.errors.BadRequestException; |
11 | 15 | import net.codestory.http.payload.Payload;
|
12 | 16 | import org.icij.swagger.FluentReader;
|
13 | 17 |
|
| 18 | +import static java.util.Optional.ofNullable; |
14 | 19 | import static org.icij.swagger.ClassUtils.findAllClassesUsingClassLoader;
|
15 | 20 |
|
16 | 21 | @Singleton
|
17 |
| -@Prefix("/api/openapi") |
| 22 | +@Prefix("/api/openapi?format=:format") |
18 | 23 | public class OpenApiResource {
|
19 |
| - @Operation(description = "Get the JSON OpenAPI v3 contract specification") |
20 |
| - @ApiResponse(responseCode = "200", description="returns the JSON file") |
| 24 | + @Operation(description = "Get the JSON or YAML OpenAPI v3 contract specification", |
| 25 | + parameters = { |
| 26 | + @Parameter(name = "format", |
| 27 | + description = "format of openapi description. Possible values are \"json\" or \"yaml\". Default=\"json\".", |
| 28 | + in = ParameterIn.QUERY) |
| 29 | + } |
| 30 | + ) |
| 31 | + @ApiResponse(responseCode = "200", description="returns the JSON or YAML file") |
21 | 32 | @Get()
|
22 |
| - public Payload get() { |
| 33 | + public Payload get(String format) { |
23 | 34 | final OpenAPI openAPI = new FluentReader().read(findAllClassesUsingClassLoader(getClass().getPackageName()));
|
24 |
| - return new Payload("text/json", Json31.mapper().convertValue(openAPI, ObjectNode.class).toString()); |
| 35 | + if ("json".equals(ofNullable(format).orElse("json"))) { |
| 36 | + return new Payload("text/json", Json31.mapper().convertValue(openAPI, ObjectNode.class).toString()); |
| 37 | + } else if ("yaml".equals(format)) { |
| 38 | + return new Payload("text/yaml", Yaml31.pretty(openAPI)); |
| 39 | + } else { |
| 40 | + throw new BadRequestException(); |
| 41 | + } |
25 | 42 | }
|
26 | 43 | }
|
0 commit comments