How to create OpenAPI schema components programmatically using OpenAPI4J parser?

Viewed 554

I need to create an OpenAPI JSON file programmatically as my endpoints have a one-to-one mapping with the tables in the database. I need to create the components (Schemas) which needs to be referenced in response object. I am not able to create the OAI3Context object as I do not have a URL which needs to be passed as argument.

OpenAPI4J Maven entry in my pom.xml:

<!-- https://mvnrepository.com/artifact/org.openapi4j/openapi-parser -->
    <dependency>
        <groupId>org.openapi4j</groupId>
        <artifactId>openapi-parser</artifactId>
        <version>1.0.7</version>
    </dependency>

Sample openapi.json file which I want to make programatically:

{
  "openapi": "3.0.2",
  "info": {
    "contact": {
      "email": "johndoe@TEST.com",
      "name": "John Doe",
      "url": "https://www.TEST.com/api/support"
    },
    "description": "TEST API based on the OpenAPI 3.0.2 specification.",
    "license": {
      "name": "TEST Inc",
      "url": "https://www.TEST.com/licences/LICENSE-2.0.html"
    },
    "termsOfService": "https://www.TEST.com/api/terms",
    "title": "TEST API - OpenAPI 3.0.2",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "http://localhost:8080/TEST-REST/api/",
      "description": "descirption1"
    }
  ],
  "tags": [
    {
      "name": "connection",
      "description": "Connection management API ",
      "externalDocs": {
        "description": "Connection management API",
        "url": "http://www.TEST.com"
      }
    },
    {
      "name": "REST API",
      "description": "TEST's non-crud APIs",
      "externalDocs": {
        "description": "TEST's non-crud APIs",
        "url": "http://www.TEST.com"
      }
    },
    {
      "name": "objects",
      "description": "TEST CRUD Operations on selected table",
      "externalDocs": {
        "description": "CRUD API TEST TEST. Can be done on selected tables",
        "url": "http://www.TEST.com"
      }
    }
  ],
  "paths": {
    "/rest/authenticate": {
      "description": "authenticate and get a token",
      "summary": "authenticate and get a connection token",
      "get": {
        "tags": [
          "connection"
        ],
        "operationId": "authenticate",
        "parameters": [
          {
            "required": true,
            "schema": {
              "description": "TEST datasource to connect to",
              "type": "string"
            },
            "in": "query",
            "name": "username"
          },
          {
            "required": true,
            "schema": {
              "description": "password of the user",
              "type": "string"
            },
            "in": "query",
            "name": "password"
          },
          {
            "required": true,
            "schema": {
              "description": "TEST datasource to connect to",
              "type": "string"
            },
            "in": "query",
            "name": "datasource"
          },
          {
            "required": true,
            "schema": {
              "description": "TEST Service to connect to",
              "type": "string"
            },
            "in": "query",
            "name": "service"
          },
          {
            "required": false,
            "schema": {
              "description": "User role",
              "type": "string"
            },
            "in": "query",
            "name": "role"
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Connection",
            "content": {
              "application/json": {
                "schema": {
                  "$ref" : "#/components/schemas/connection"
                }
              },
              "application/xml": {
                "schema": {
                  "$ref" : "#/components/schemas/connection"
                }
              }
            }
          },
          "405": {
            "description": "Invalid input"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "connection": {
        "required": [
          "connid"
        ],
        "type": "object",
        "properties": {
          "connid": {
            "type": "string",
            "example": "TEST1_107c5a8c1799d4cf8bb5ce295ab38954"
          }
        }
      }
    }
  }
}

My Java code:

package vish.api.test2;

import org.openapi4j.core.exception.EncodeException;

import org.openapi4j.parser.model.SerializationFlag;
import org.openapi4j.parser.model.v3.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class OpenAPICreator {

  public static void main(String[] args) {


    try {
      OpenApi3 openApi3 = new OpenApi3();
      openApi3.setOpenapi("3.0.2");
      Info info = new Info();
      openApi3.setInfo(info);
      info.setTitle("vish API - OpenAPI 3.0.2");
      info.setDescription("vish API based on the OpenAPI 3.0.2 specification.");
      info.setTermsOfService("https://www.vish.com/api/terms");

      Contact contact = new Contact();
      contact.setName("Avik Chatterjee");
      contact.setEmail("achatterjee@vish.com");
      contact.setUrl("https://www.vish.com/api/support");
      info.setContact(contact);

      Components components = new Components();
      Schema schema = new Schema();
      components.setSchema("test", schema);

      Schema schema2 = new Schema();
      schema.setProperty("test2", schema2);
      openApi3.setComponents(components);

      String canonicalRef = schema2.getCanonicalRef();

      System.out.println("canonicalRef = " + canonicalRef);



      License license = new License();
      license.setName("vish Inc");
      license.setUrl("https://www.vish.com/licences/LICENSE-2.0.html");
      info.setLicense(license);
      info.setVersion("1.0.0");

      ExternalDocs externalDocs = new ExternalDocs();
      externalDocs.setDescription("vish API Description");
      externalDocs.setUrl("https://www.vish.com");

      Server server1 = new Server();
      server1.setDescription("descirption1");
      server1.setUrl("http://localhost:8080/LIMS-REST/api/");

     /* Server server2  = new Server();
      server2.setDescription("test diff descirption1");
      server2.setUrl("http://localhost:8080/LIMS-REST/api/");*/
      ArrayList<Server> serverArrayList = new ArrayList<>();
      serverArrayList.add(server1);
      //serverArrayList.add(server2);
      openApi3.setServers(serverArrayList);

      Tag connectionTag = new Tag();
      Tag restTag = new Tag();
      Tag objectsTag = new Tag();

      List<Tag> tagList = new ArrayList<>();
      tagList.add(connectionTag);
      tagList.add(restTag);

      tagList.add(objectsTag);

      connectionTag.setName("connection");
      connectionTag.setDescription("Connection management API ");
      ExternalDocs authDocs = new ExternalDocs();
      authDocs.setDescription("Connection management API");
      authDocs.setUrl("http://www.vish.com");
      connectionTag.setExternalDocs(authDocs);

      restTag.setName("REST API");
      restTag.setDescription("vish's non-crud APIs");
      ExternalDocs listWFDocs = new ExternalDocs();
      listWFDocs.setDescription("vish's non-crud APIs");
      listWFDocs.setUrl("http://www.vish.com");
      restTag.setExternalDocs(listWFDocs);

      objectsTag.setName("objects");
      objectsTag.setDescription("vish CRUD Operations on selected table");
      ExternalDocs crudDocs = new ExternalDocs();
      crudDocs.setDescription("CRUD API vish LIMS. Can be done on selected tables");
      crudDocs.setUrl("http://www.vish.com");
      objectsTag.setExternalDocs(crudDocs);

      openApi3.setTags(tagList);


      Schema connectionSchema = new Schema();
//      connectionSchema.setre
//      connectionSchema.setReference(oai3Context, new URL("http://localhost:8080/TEST-REST/"), "connection" );
      components.setSchema("connection", connectionSchema);
      connectionSchema.setType("Object");
      Schema connIdSchema = new Schema();
      connectionSchema.setType("string");
      connectionSchema.setExample("TEST1_107c5a8c1799d4cf8bb5ce295ab38954");
      connectionSchema.setProperty("connid", connIdSchema);

      Path authPath = new Path();
      Operation authOps = new Operation();

      authPath.setOperation("get", authOps);
      authPath.setDescription("authenticate and get a token");
      authPath.setSummary("authenticate and get a connection token");
      authOps.addTag(connectionTag.getName());
      authOps.setOperationId("authenticate");

      Parameter username = new Parameter();
      username.setName("username");
      username.setIn("query");
      username.setRequired(true);
      Schema userSchema = new Schema();
      userSchema.setDescription("TEST datasource to connect to");
      userSchema.setType("string");
      username.setSchema(userSchema);

      authOps.addParameter(username);

      Parameter password = new Parameter();
      password.setName("password");
      password.setIn("query");
      password.setRequired(true);
      password.setRequired(true);
      Schema pwdSchema = new Schema();
      pwdSchema.setDescription("password of the user");
      pwdSchema.setType("string");
      password.setSchema(pwdSchema);
      authOps.addParameter(password);

      Parameter database = new Parameter();
      database.setName("datasource");
      database.setIn("query");
      database.setRequired(true);
      Schema dbSchema = new Schema();
      dbSchema.setDescription("TEST datasource to connect to");
      dbSchema.setType("string");
      database.setSchema(dbSchema);
      authOps.addParameter(database);

      Parameter service = new Parameter();
      service.setName("service");
      service.setIn("query");
      service.setRequired(true);
      Schema serviceSchema = new Schema();
      serviceSchema.setDescription("TEST Service to connect to");
      serviceSchema.setType("string");
      service.setSchema(serviceSchema);
      authOps.addParameter(service);

      Parameter role = new Parameter();
      role.setName("role");
      role.setIn("query");
      role.setRequired(false);
      Schema roleSchema = new Schema();
      roleSchema.setDescription("User role");
      roleSchema.setType("string");
      role.setSchema(roleSchema);
      authOps.addParameter(role);

      Response resp_200 = new Response();
      resp_200.setDescription("Successful Connection");
      MediaType mediaType = new MediaType();
      Schema resp200Schema = new Schema();
//      resp200Schema.setReference(oai3Context, new URL("http://localhost:8080/TEST-REST/"), "connection");
      mediaType.setSchema(resp200Schema);
      resp_200.setContentMediaType("application/json", mediaType);
      authOps.setResponse("200", resp_200);


      Map<String, Path> pathMap = new HashMap<>();
      pathMap.put("/rest/authenticate", authPath);
//      pathMap.put("/rest/close", closePath);
      openApi3.setPaths(pathMap);


      SerializationFlag outAsJson = SerializationFlag.OUT_AS_JSON;
      EnumSet<SerializationFlag> enumSet = EnumSet.of(outAsJson);

      String openAPIJson = openApi3.toString(enumSet);


      SerializationFlag outAsYaml = SerializationFlag.OUT_AS_YAML;
      EnumSet<SerializationFlag> enumYamlSet = EnumSet.of(outAsYaml);


      String yaml = openApi3.toString(enumYamlSet);

      FileOutputStream fos1 = new FileOutputStream(new File("vish1.json"));
      FileOutputStream fos2 = new FileOutputStream(new File("vish1.yaml"));

      fos1.write(openAPIJson.getBytes(StandardCharsets.UTF_8));
      fos2.write(yaml.getBytes(StandardCharsets.UTF_8));

      //  System.out.println("gson way = \n" + gson.toJson(openApi3) );
    } catch (EncodeException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

To sum up, how do I create the following programmatically without creating an OpenAPI3Context and refer the component in my 'responses'?

  "components": {
    "schemas": {
      "connection": {
        "required": [
          "connid"
        ],
        "type": "object",
        "properties": {
          "connid": {
            "type": "string",
            "example": "TEST1_107c5a8c1799d4cf8bb5ce295ab38954"
          }
        }
      }
    }
  }
0 Answers
Related