简体   繁体   中英

How to build and return an OpenApi 3.0 Document programmatically in a Spring GET endpoint?

i have a requirement where i need to have a GET endpoint in my microservice that returns an io.swagger.v3.oas.models.OpenAPI document, and i am wondering how to compose that object. The object in raw form looks like this:

{
"openapi": "3.0.1",
"info": {
"title": "MY API",
"description": "API for accessing stuff and other stuff.",
"termsOfService": "http://website.com",
"contact": {
  "name": "Some chap",
  "url": "https://website.com/s/url",
  "email": "alwaysReplyAll@office.com"
},
"version": "1.0"
},
"paths": {
"/v1/user/{id}/properties": {
  "get": { ...etc etc

ive tried this but the document is just coming up null/blank:

@GetMapping("/openapi3")
public @ResponseBody OpenAPI swag() {
     OpenAPI swagDoc = new OpenAPI();
     GenericOpenApiContextBuilder builder = new GenericOpenApiContextBuilder();

    try {
        swagDoc = builder.buildContext(true).read();
    } catch (OpenApiConfigurationException e) {
        // handle error        
}
    return swagDoc;
}

i have read about springfox but the examples in their docs arent very clear ... and im wondering if that is even necessary. what am i not doing right with this builder?

using Gradle btw

Per the discussion in comments, you can modify this method, you don't need to use WebClient. I have to get at the doc in my swagger service and I use this code. You wouldn't return an OpenAPI object, you'd just return a string since you already have the raw json.

getV2SwaggerDoc(new URL("..."));

private String getV2SwaggerDoc(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();

    connection.setRequestMethod(RequestMethod.GET.toString());

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

    StringBuffer stringBuffer = new StringBuffer();

    String line;

    while ((line = reader.readLine()) != null)
        stringBuffer.append(line);

    reader.close();

    connection.disconnect();

    return stringBuffer.toString();
}

i was able to simplify the accepted answer by leveraging Spring's RestTemplate instead of java's low level HTTP lib

private String retrieveSwaggerJson(String url) {
    return new RestTemplate()
            .getForEntity(url, String.class)
            .getBody();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM