Skip to content

Commit

Permalink
feat: allows to return OpenAPI yaml format
Browse files Browse the repository at this point in the history
Co-authored-by: Maxime Vanza Lutonda <[email protected]>
  • Loading branch information
bamthomas and mvanzalu committed Dec 24, 2024
1 parent 4c11347 commit 219b7a5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,41 @@
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.inject.Singleton;
import io.swagger.v3.core.util.Json31;
import io.swagger.v3.core.util.Yaml31;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.models.OpenAPI;
import net.codestory.http.annotations.Get;
import net.codestory.http.annotations.Prefix;
import net.codestory.http.errors.BadRequestException;
import net.codestory.http.payload.Payload;
import org.icij.swagger.FluentReader;

import static java.util.Optional.ofNullable;
import static org.icij.swagger.ClassUtils.findAllClassesUsingClassLoader;

@Singleton
@Prefix("/api/openapi")
@Prefix("/api/openapi?format=:format")
public class OpenApiResource {
@Operation(description = "Get the JSON OpenAPI v3 contract specification")
@ApiResponse(responseCode = "200", description="returns the JSON file")
@Operation(description = "Get the JSON or YAML OpenAPI v3 contract specification",
parameters = {
@Parameter(name = "format",
description = "format of openapi description. Possible values are \"json\" or \"yaml\". Default=\"json\".",
in = ParameterIn.QUERY)
}
)
@ApiResponse(responseCode = "200", description="returns the JSON or YAML file")
@Get()
public Payload get() {
public Payload get(String format) {
final OpenAPI openAPI = new FluentReader().read(findAllClassesUsingClassLoader(getClass().getPackageName()));
return new Payload("text/json", Json31.mapper().convertValue(openAPI, ObjectNode.class).toString());
if ("json".equals(ofNullable(format).orElse("json"))) {
return new Payload("text/json", Json31.mapper().convertValue(openAPI, ObjectNode.class).toString());
} else if ("yaml".equals(format)) {
return new Payload("text/yaml", Yaml31.pretty(openAPI));
} else {
throw new BadRequestException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ public void test_get() {
haveType("text/json").
contain("\"openapi\":\"3.0.1\"");
}
@Test
public void test_get_yaml() {
get("/api/openapi?format=yaml").should().respond(200).
haveType("text/yaml").
contain("openapi: 3.0.1");
}

@Before
public void setUp() {
Expand Down

0 comments on commit 219b7a5

Please sign in to comment.