Installing libopenapi
Start parsing OpenAPI specs in seconds.Grab the latest release of libopenapi.
Load an OpenAPI spec into a model
import (
"fmt"
"github.com/pb33f/libopenapi"
"os"
)
func readSpec() {
// load an OpenAPI 3 specification from bytes
petstore, _ := os.ReadFile("test_specs/petstorev3.json")
// create a new document from specification bytes
document, err := libopenapi.NewDocument(petstore)
// if anything went wrong, an error is thrown
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}
// because we know this is a v3 spec, we can build a ready to go model from it.
v3Model, err := document.BuildV3Model()
// if anything went wrong when building the v3 model, errors (will be joined) are returned
if err != nil {
panic(fmt.Sprintf("cannot create v3 model from document: %e", err))
}
// get a count of the number of paths and schemas.
paths := v3Model.Model.Paths.PathItems.Len()
schemas := v3Model.Model.Components.Schemas.Len()
// print the number of paths and schemas in the document
fmt.Printf("There are %d paths and %d schemas in the document", paths, schemas)
}
This will print the following to the console: