RepreZen / KaiZen-OpenApi-Parser

High-performance Parser, Validator, and Java Object Model for OpenAPI 3.x
130 stars 31 forks source link

<newbie question>can i use this library to compose a full fledged swagger document from separate path snippets and schema snippets? #229

Open lekkalapudi opened 5 years ago

lekkalapudi commented 5 years ago

can i use this library to compose a full fledged swagger document from separate path snippets and schema snippets?

chris-brace commented 5 years ago

basically, yes, you can. look up refs and then do something like this


package oas3;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.reprezen.jsonoverlay.Overlay;
import com.reprezen.jsonoverlay.SerializationOptions;
import com.reprezen.kaizen.oasparser.OpenApi3Parser;
import com.reprezen.kaizen.oasparser.model3.OpenApi3;
import com.reprezen.kaizen.oasparser.val.ValidationResults;

import java.io.FileWriter;
import java.net.URL;

public class Main
{
    public static void main(String[] args) throws Exception
    {
        if (args.length != 1)
        {
            throw new IllegalArgumentException("Must have 1 command line param of target location.");
        }

        final String outFile = args[0];

        if (outFile == null || outFile.isBlank())
        {
            throw new IllegalArgumentException("Initial argument must be a path.");
        }

        final URL uri = Main.class.getClassLoader().getResource("api.yaml");
        final OpenApi3 model = new OpenApi3Parser().parse(uri);

        if (!model.isValid())
        {
            throw new Exception("Invalid model.");
        }

        final JsonNode serial = Overlay.of(model).toJson(SerializationOptions.Option.FOLLOW_REFS);
        final String raw = new YAMLMapper().writerWithDefaultPrettyPrinter().writeValueAsString(serial);

        // If we get here, write the file.
        try (final FileWriter fw = new FileWriter(outFile, false))
        {
            fw.write(raw);
        }
    }
}
tedepstein commented 5 years ago

Nice assist, @chris-brace . Thanks!