### Install libopenapi Go Package Source: https://github.com/pb33f/libopenapi/blob/main/README.md Use go get to download and install the libopenapi library into your Go project. ```bash go get github.com/pb33f/libopenapi ``` -------------------------------- ### Iterate Over Paths Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Example of how to iterate through the path names defined in the Paths model. ```go for pathName := range model.Model.Paths.PathItems { pathItem := model.Model.Paths.PathItems[pathName] fmt.Printf("Path: %s\n", pathName) } ``` -------------------------------- ### Download Petstore OpenAPI Specification Source: https://github.com/pb33f/libopenapi/blob/main/README.md Use curl to download the petstorev3.json file, which will be used as an example input. ```bash curl https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/_archive_/schemas/v3.0/pass/petstore.yaml > petstorev3.json ``` -------------------------------- ### Handle Bundling Errors Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-bundler.md Example of how to handle errors that may occur during the bundling process. This includes checking for nil errors and potentially handling specific error types. ```go bundled, err := bundler.BundleBytes(specBytes, config) if err != nil { fmt.Printf("Bundling failed: %v\n", err) // Handle specific error types if needed } ``` -------------------------------- ### Iterate Over Schema Properties Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Example of how to iterate through the properties of a schema object. ```go if schema.Properties != nil { for propName := range schema.Properties.FromOldest() { prop := schema.Properties.GetByName(propName) fmt.Printf("Property: %s (type: %s)\n", propName, prop.Type) } } ``` -------------------------------- ### Walking the Document Tree Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Iterate through the document's paths and components to access and print information about API endpoints and schemas. This example demonstrates accessing titles, versions, path names, operations, schema names, and property types. ```go doc, _ := libopenapi.NewDocument(specBytes) model, _ := doc.BuildV3Model() // Access info fmt.Printf("API: %s v%s\n", model.Model.Info.Title, model.Model.Info.Version) // Walk paths if model.Model.Paths != nil { for pathName := range model.Model.Paths.PathItems { pathItem := model.Model.Paths.PathItems[pathName] fmt.Printf("Path: %s\n", pathName) // Check operations if pathItem.Get != nil { fmt.Printf(" GET %s\n", pathItem.Get.Summary) } if pathItem.Post != nil { fmt.Printf(" POST %s\n", pathItem.Post.Summary) } } } // Walk components if model.Model.Components != nil && model.Model.Components.Schemas != nil { for schemaName := range model.Model.Components.Schemas.FromOldest() { schema := model.Model.Components.Schemas.GetByName(schemaName) fmt.Printf("Schema: %s (type: %s)\n", schemaName, schema.Type) if schema.Properties != nil { for propName := range schema.Properties.FromOldest() { prop := schema.Properties.GetByName(propName) fmt.Printf(" %s: %s\n", propName, prop.Type) } } } } ``` -------------------------------- ### Bundle Bytes with Origin Tracking Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-bundler.md Example of bundling specification bytes while tracking origins. Use this when you need to map bundled components back to their original source files. ```go result, err := bundler.BundleBytesComposedWithOrigins(specBytes, config, compositionConfig) if err != nil { panic(err) } // Access the bundled spec bundledBytes := result.Bytes // Map components back to sources for componentPath, origin := range result.Origins { fmt.Printf("%s came from %s\n", componentPath, origin.AbsPath) } ``` -------------------------------- ### Process Multiple Specs with Memory Cleanup Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Example function demonstrating how to process multiple specifications and properly release resources (doc and caches) to prevent memory accumulation. ```go func processMultipleSpecs(specs [][]byte) { for _, specBytes := range specs { doc, _ := libopenapi.NewDocument(specBytes) model, _ := doc.BuildV3Model() // Use index/model // Clean up doc.Release() libopenapi.ClearAllCaches() } } ``` -------------------------------- ### OrderedMap Usage Examples Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Demonstrates common operations with OrderedMap, including getting a value by name, iterating in insertion order, and getting the map's length. ```go // Get a value by name value := orderedMap.GetByName("Pet") ``` ```go // Iterate in insertion order for name := range orderedMap.FromOldest() { value := orderedMap.GetByName(name) } ``` ```go // Get length count := orderedMap.Len() ``` -------------------------------- ### Get Document Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Retrieves the current configuration controlling reference handling and file access behavior for the document. ```go func (d Document) GetConfiguration() *datamodel.DocumentConfiguration ``` -------------------------------- ### Get Operation Parameters Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Retrieve and display details for parameters of a specific operation (e.g., GET /pets/{id}), including name, location, required status, and schema type. ```go op := model.Model.Paths.PathItems["/pets/{id}"].Get if op != nil && op.Parameters != nil { for _, param := range op.Parameters { fmt.Printf("Parameter: %s\n", param.Name) fmt.Printf(" In: %s (path/query/header/cookie)\n", param.In) fmt.Printf(" Required: %v\n", param.Required) if param.Schema != nil { fmt.Printf(" Type: %s\n", param.Schema.Type) } } } ``` -------------------------------- ### Get Raw Specification Info Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Returns raw specification details including the root node, file type, detected format, and original indentation. ```go func (d Document) GetSpecInfo() *datamodel.SpecInfo ``` -------------------------------- ### Configuration with All Options Enabled Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/configuration.md Enable all reference resolution options for comprehensive parsing. This includes local, file, and remote references, along with sequential extraction. ```go config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, AllowRemoteReferences: true, BasePath: "/local/specs", BaseURL: &url.URL{Scheme: "https", Host: "api.example.com"}, ExtractRefsSequentially: true, } doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) ``` -------------------------------- ### Get Operation Responses Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Retrieves and prints status codes, descriptions, and content types for responses of a GET operation. ```go op := model.Model.Paths.PathItems["/pets"].Get if op != nil && op.Responses != nil { // Get all status codes for statusCode := range op.Responses.Codes.FromOldest() { response := op.Responses.Codes.GetByName(statusCode) fmt.Printf("Response: %s\n", statusCode) fmt.Printf(" Description: %s\n", response.Description) if response.Content != nil { for mediaType := range response.Content.FromOldest() { mt := response.Content.GetByName(mediaType) fmt.Printf(" %s", mediaType) if mt.Schema != nil { fmt.Printf(" (type: %s)", mt.Schema.Type) } fmt.Printf("\n") } } } } ``` -------------------------------- ### Access Server Information Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Retrieves and prints global and path-specific server information, including URLs and descriptions. ```go // Global servers for _, server := range model.Model.Servers { fmt.Printf("Server: %s\n", server.Url) fmt.Printf(" Description: %s\n", server.Description) } // Path-specific servers pathItem := model.Model.Paths.PathItems["/pets"] if pathItem.Servers != nil { for _, server := range pathItem.Servers { fmt.Printf("Override server: %s\n", server.Url) } } ``` -------------------------------- ### Create New OpenAPI Document with Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Creates a new OpenAPI document with explicit configuration for reference handling. Allows control over file and remote reference resolution. ```go func NewDocumentWithConfiguration(specByteArray []byte, configuration *datamodel.DocumentConfiguration) (Document, error) ``` ```go config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, AllowRemoteReferences: true, BaseURL: "file:///specs/", } doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) if err != nil { panic(err) } ``` -------------------------------- ### Get OpenAPI Version Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Retrieves the OpenAPI/Swagger version string from the parsed specification. ```go func (d Document) GetVersion() string ``` -------------------------------- ### Bundle Document with Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-bundler.md Bundles an OpenAPI 3.x document model with advanced inline configuration options. Useful for controlling how references are inlined. ```go func BundleDocumentWithConfig(model *v3.Document, bundleConfig *BundleInlineConfig) ([]byte, error) ``` ```go model, err := doc.BuildV3Model() inlineTrue := true config := &bundler.BundleInlineConfig{ InlineLocalRefs: &inlineTrue, } bundled, err := bundler.BundleDocumentWithConfig(&model.Model, config) if err != nil { panic(err) } ``` -------------------------------- ### Get Rolodex Instance Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Returns the Rolodex instance used for reference resolution. This is nil if no model has been built yet. ```go func (d Document) GetRolodex() *index.Rolodex ``` -------------------------------- ### Iterate Safe Circular References Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Example of iterating through safe circular references found in the model's index. ```go for _, cirRef := range model.Index.GetRolodex().GetSafeCircularReferences() { fmt.Printf("Safe circular ref: %s\n", cirRef.Reference) fmt.Printf(" Location: %s\n", cirRef.Location) fmt.Printf(" Array loop: %v\n", cirRef.IsArrayLoop) fmt.Printf(" Polymorphic: %v\n", cirRef.IsPolymorphic) } ``` -------------------------------- ### Direct Component Lookup by Reference Path Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Shows how to directly look up a component using its reference path within the index. Handles both internal and external references. ```go // Direct lookup by reference path petNode := index.FindComponent("#/components/schemas/Pet") // Check if it exists if petNode != nil { // Component found } // For external references, the reference will be resolved if // the external file was indexed userNode := index.FindComponent("#/definitions/User") ``` -------------------------------- ### Get Request Body Details Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Extracts and prints the description, required status, and media types of a request body for a specific operation. ```go op := model.Model.Paths.PathItems["/pets"].Post if op != nil && op.RequestBody != nil { fmt.Printf("Request Body:\n") fmt.Printf(" Description: %s\n", op.RequestBody.Description) fmt.Printf(" Required: %v\n", op.RequestBody.Required) // List supported media types if op.RequestBody.Content != nil { for mediaType := range op.RequestBody.Content.FromOldest() { fmt.Printf(" Media Type: %s\n", mediaType) } } } ``` -------------------------------- ### Minimal Configuration for Parsing Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/configuration.md Use this minimal configuration when parsing a specification that does not contain external references. ```go doc, err := libopenapi.NewDocument(specBytes) ``` -------------------------------- ### MediaType Data Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Describes the content for a specific media type within a request or response. It links to a schema and can include examples. ```go type MediaType struct { Schema *Schema Example interface{} Examples *OrderedMap Encoding *OrderedMap } ``` -------------------------------- ### Document Creation Functions Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Provides functions to create a new Document instance from byte arrays, with or without configuration and type checking. ```go func NewDocument(specByteArray []byte) (Document, error) ``` ```go func NewDocumentWithConfiguration(specByteArray []byte, configuration *datamodel.DocumentConfiguration) (Document, error) ``` ```go func NewDocumentWithTypeCheck(specByteArray []byte, bypassCheck bool) (Document, error) ``` -------------------------------- ### RequestBody Data Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Describes the payload of an API request. It includes a description and the content, which maps media types to their schema and examples. ```go type RequestBody struct { Description string Content *OrderedMap // Key: media type, Value: MediaType Required bool } ``` -------------------------------- ### Accessing Raw AST Details (Low-Level API) Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Shows how to use the low-level API to access Abstract Syntax Tree (AST) details, such as line and column numbers, from an OpenAPI model. ```go model, _ := doc.BuildV3Model() // Go low to access AST details lowDoc := model.Model.GoLow() // Access raw node information fmt.Printf("Document starts at line %d, column %d\n", lowDoc.Version.KeyNode.Line, lowDoc.Version.KeyNode.Column) // For paths for path := range model.Model.Paths.PathItems { lowPath := model.Model.Paths.PathItems[path].GoLow() fmt.Printf("Path '%s' at line %d\n", path, lowPath.KeyNode.Line) } ``` -------------------------------- ### Get Root Index from Rolodex Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Retrieves the SpecIndex for the root document managed by the Rolodex. This is useful for accessing the primary document's index. ```go doc, _ := libopenapi.NewDocument(specBytes) model, _ := doc.BuildV3Model() rolodex := model.Index.GetRolodex() rootIndex := rolodex.GetRootIndex() fmt.Printf("Root index found: %v\n", rootIndex != nil) ``` -------------------------------- ### Load OpenAPI Document Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Load an OpenAPI specification from a file and create a new document object. Panics on error. ```go import ( "github.com/pb33f/libopenapi" "os" ) func main() { // Read spec file specBytes, err := os.ReadFile("openapi.yaml") if err != nil { panic(err) } // Create document doc, err := libopenapi.NewDocument(specBytes) if err != nil { panic(err) } // Build model (OpenAPI 3.x) model, err := doc.BuildV3Model() if err != nil { panic(err) } // Now model.Model contains the parsed OpenAPI document } ``` -------------------------------- ### Bundle Bytes with Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-bundler.md Bundles OpenAPI specification bytes with advanced inline configuration options. Allows fine-grained control over bundling behavior. ```go func BundleBytesWithConfig(bytes []byte, configuration *datamodel.DocumentConfiguration, bundleConfig *BundleInlineConfig) ([]byte, error) ``` ```go inlineTrue := true bundleConfig := &bundler.BundleInlineConfig{ InlineLocalRefs: &inlineTrue, ResolveDiscriminatorExternalRefs: &inlineTrue, } bundled, err := bundler.BundleBytesWithConfig(specBytes, docConfig, bundleConfig) if err != nil { panic(err) } ``` -------------------------------- ### v3.MediaType Struct Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Defines the content for a specific media type within a request or response in an OpenAPI 3.x specification. It can include schema, examples, and encoding details. ```go type v3.MediaType struct { Schema *base.Schema Example interface{} Examples *orderedmap.Map[string, *Example] Encoding *orderedmap.Map[string, *Encoding] } ``` -------------------------------- ### Configuration for Local File References Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/configuration.md Enable this configuration for multi-file specifications that use local file references. Set the BasePath to the directory containing the specification files. ```go config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, BasePath: "/path/to/api-spec", SpecFilePath: "openapi.yaml", } doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) ``` -------------------------------- ### Access Security Requirements Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Demonstrates how to access global and operation-specific security requirements, including schemes and scopes. ```go // Global security for _, secReq := range model.Model.Security { // Each secReq is a map of scheme names to required scopes // for _, schemeName := range secReq.GetRequiredSchemes() { ... } } // Operation-specific security op := model.Model.Paths.PathItems["/pets"].Get if op.Security != nil { for _, secReq := range op.Security { // Operation-level security overrides global } } ``` -------------------------------- ### Bundle Bytes With Config Function Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Bundles specification bytes with inline configuration. ```go func bundler.BundleBytesWithConfig(bytes []byte, configuration *datamodel.DocumentConfiguration, bundleConfig *BundleInlineConfig) ([]byte, error) ``` -------------------------------- ### Access Index and Rolodex from Document Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Demonstrates how to access the index and rolodex from a built V3 model, including retrieving all indexes and checking for circular references. ```go doc, _ := libopenapi.NewDocument(specBytes) model, _ := doc.BuildV3Model() // Access the index index := model.Index // Access the rolodex rolodex := index.GetRolodex() // Get all indexes (root + external files) allIndexes := rolodex.GetIndexes() // Check for circular references safeCircRefs := rolodex.GetSafeCircularReferences() infiniteCircRefs := rolodex.GetInfiniteCircularReferences() ``` -------------------------------- ### Custom Remote Handler with Authentication Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/configuration.md Implement a custom remote URL handler that includes authentication headers for fetching remote documents. This example uses a Bearer token. ```go customHandler := func(url string) ([]byte, error) { req, _ := http.NewRequest("GET", url, nil) req.Header.Set("Authorization", "Bearer "+apiToken) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() return io.ReadAll(resp.Body) } config := &datamodel.DocumentConfiguration{ AllowRemoteReferences: true, RemoteURLHandler: customHandler, } ``` -------------------------------- ### Configure Processing Options Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/configuration.md Adjust document processing behavior, such as skipping index builds or document checks, and controlling reference extraction and bundling. Use sequential extraction for bundling. ```go config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, BasePath: "/specs", ExtractRefsSequentially: true, // Required for bundling } doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) model, err := doc.BuildV3Model() // Now safe to bundle bundled, err := bundler.BundleDocument(&model.Model) ``` -------------------------------- ### Get Infinite Circular References from Rolodex Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Retrieves circular references that cannot be broken and may lead to infinite loops. This is critical for detecting and preventing infinite recursion during document traversal. ```go infiniteRefs := rolodex.GetInfiniteCircularReferences() if len(infiniteRefs) > 0 { fmt.Printf("WARNING: %d infinite circular references detected\n", len(infiniteRefs)) for _, ref := range infiniteRefs { fmt.Printf(" %s\n", ref.Reference) } } ``` -------------------------------- ### v3.PathItem Struct Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Defines the operations available on a specific path in an OpenAPI 3.x specification. It can include summary, description, servers, parameters, and various HTTP methods (GET, POST, etc.). ```go type v3.PathItem struct { Summary string Description string Servers []*Server Parameters []*Parameter Get *Operation Post *Operation Put *Operation Delete *Operation Patch *Operation Head *Operation Options *Operation Trace *Operation } ``` -------------------------------- ### Get Safe Circular References from Rolodex Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-index.md Retrieves circular references that can be safely broken using array or alternative composition (oneOf/anyOf). Useful for identifying potentially problematic but resolvable references. ```go rolodex := model.Index.GetRolodex() safeRefs := rolodex.GetSafeCircularReferences() for _, ref := range safeRefs { fmt.Printf("Safe circular ref: %s\n", ref.Reference) } ``` -------------------------------- ### Access Schema Properties Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Iterate through the properties of a specific schema (e.g., 'Pet') and print each property's name, type, description, and whether it's required. ```go schema := model.Model.Components.Schemas.GetByName("Pet") if schema.Properties != nil { for propName := range schema.Properties.FromOldest() { prop := schema.Properties.GetByName(propName) fmt.Printf("Property: %s\n", propName) fmt.Printf(" Type: %s\n", prop.Type) fmt.Printf(" Description: %s\n", prop.Description) // Check if required isRequired := false for _, req := range schema.Required { if req == propName { isRequired = true break } } fmt.Printf(" Required: %v\n", isRequired) } } ``` -------------------------------- ### Analyze OpenAPI Endpoints Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/INDEX.md Iterates through all paths in an OpenAPI model to find and print details about HTTP methods like GET, including their summary. Useful for discovering available API endpoints. ```go for pathName := range model.Model.Paths.PathItems { pathItem := model.Model.Paths.PathItems[pathName] if pathItem.Get != nil { fmt.Printf("GET %s: %s\n", pathName, pathItem.Get.Summary) } } ``` -------------------------------- ### New Document Configuration Function Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Creates a new default DocumentConfiguration object. ```go func datamodel.NewDocumentConfiguration() *DocumentConfiguration ``` -------------------------------- ### v3.Parameter Struct Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Defines an operation parameter or path item parameter in an OpenAPI 3.x specification. It includes name, location (query, header, path, cookie), description, schema, and example values. ```go type v3.Parameter struct { Name string In string // "query", "header", "path", "cookie" Description string Required bool Deprecated bool AllowEmptyValue bool Style string Explode *bool AllowReserved *bool Schema *base.Schema Example interface{} Examples *orderedmap.Map[string, *Example] } ``` -------------------------------- ### List All Endpoints in OpenAPI Document Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Iterate through all paths in the OpenAPI document and print the HTTP method, path, and summary for each operation. ```go for pathName := range model.Model.Paths.PathItems { pathItem := model.Model.Paths.PathItems[pathName] methods := []struct { name string op *v3.Operation }{ {"GET", pathItem.Get}, {"POST", pathItem.Post}, {"PUT", pathItem.Put}, {"DELETE", pathItem.Delete}, {"PATCH", pathItem.Patch}, {"HEAD", pathItem.Head}, {"OPTIONS", pathItem.Options}, {"TRACE", pathItem.Trace}, } for _, m := range methods { if m.op != nil { fmt.Printf("%s %s - %s\n", m.name, pathName, m.op.Summary) } } } ``` -------------------------------- ### Apply Overlay From Bytes to Spec Bytes Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-overlay.md Applies an overlay to target document bytes when both are provided as raw bytes. The returned OverlayDocument uses a default configuration, suitable when custom configuration is not needed. ```go func ApplyOverlayFromBytesToSpecBytes(docBytes, overlayBytes []byte) (*OverlayResult, error) ``` ```go result, err := libopenapi.ApplyOverlayFromBytesToSpecBytes(docBytes, overlayBytes) if err != nil { panic(err) } // Build a model from the result model, err := result.OverlayDocument.BuildV3Model() if err != nil { panic(err) } // Access the raw bytes modifiedYAML := result.Bytes // Check for warnings for _, warning := range result.Warnings { fmt.Printf("Warning: %s\n", warning) } ``` -------------------------------- ### Accessing OpenAPI v3 Paths and Schemas (High-Level API) Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Demonstrates how to use the high-level API to iterate through paths and access schema information within an OpenAPI v3 document. ```go doc, _ := libopenapi.NewDocument(specBytes) model, _ := doc.BuildV3Model() // Access paths directly for path, pathItem := range model.Model.Paths.PathItems { fmt.Printf("Path: %s\n", path) if pathItem.Get != nil { fmt.Printf(" GET: %s\n", pathItem.Get.Summary) } } // Access components for schemaName := range model.Model.Components.Schemas.FromOldest() { schema := model.Model.Components.Schemas.GetByName(schemaName) fmt.Printf("Schema: %s (type: %s)\n", schemaName, schema.Type) } ``` -------------------------------- ### v3.Server Struct Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Defines connection information to a target server within an OpenAPI specification. Includes URL, description, and variables. ```go type v3.Server struct { Url string Description string Variables *orderedmap.Map[string, *ServerVariable] } ``` -------------------------------- ### Overlay Document Creation Function Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Creates a new overlay document from a byte array. ```go func NewOverlayDocument(overlayBytes []byte) (*highoverlay.Overlay, error) ``` -------------------------------- ### Parse OpenAPI File and Build V3 Model Source: https://github.com/pb33f/libopenapi/blob/main/README.md This Go code snippet demonstrates how to read an OpenAPI JSON file, create a new document using libopenapi, and then build the OpenAPI v3 model. It includes error handling for file reading and document creation. ```go package main import ( "fmt" "os" "github.com/pb33f/libopenapi" ) func main() { petstore, _ := os.ReadFile("petstorev3.json") document, err := libopenapi.NewDocument(petstore) if err != nil { panic(fmt.Sprintf("cannot create new document: %e", err)) } docModel, err := document.BuildV3Model() if err != nil { panic(fmt.Sprintf("cannot create v3 model from document: %e", err)) } // The following fails after the first iteration for schemaName, schema := range docModel.Model.Components.Schemas.FromOldest() { if schema.Schema().Properties != nil { fmt.Printf("Schema '%s' has %d properties\n", schemaName, schema.Schema().Properties.Len()) } } } ``` -------------------------------- ### Process Single OpenAPI Document with Memory Management Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Shows how to load, process, and release memory for a single OpenAPI document using `defer` for cleanup. ```go func processSpec(filename string) error { specBytes, err := os.ReadFile(filename) if err != nil { return err } doc, err := libopenapi.NewDocument(specBytes) if err != nil { return err } defer doc.Release() // Clean up when done model, err := doc.BuildV3Model() if err != nil { return err } // Use model return analyzeSpec(model) } ``` -------------------------------- ### DocumentConfiguration Type Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Configuration for document creation and reference resolution. Includes settings for base URL, file paths, reference handling, and logging. ```go type datamodel.DocumentConfiguration struct { BaseURL *url.URL RemoteURLHandler utils.RemoteURLHandler BasePath string SpecFilePath string FileFilter []string RemoteFS fs.FS LocalFS fs.FS AllowFileReferences bool SkipExternalRefResolution bool AllowRemoteReferences bool AvoidIndexBuild bool BypassDocumentCheck bool SkipJSONConversion bool IgnorePolymorphicCircularReferences bool IgnoreArrayCircularReferences bool SkipCircularReferenceCheck bool Logger *slog.Logger ExtractRefsSequentially bool ExcludeExtensionRefs bool BundleInlineRefs bool } ``` -------------------------------- ### List All Schemas in OpenAPI Document Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Iterate through all schemas defined in the components section of the OpenAPI document and print their name, type, and description. ```go if model.Model.Components != nil && model.Model.Components.Schemas != nil { for schemaName := range model.Model.Components.Schemas.FromOldest() { schema := model.Model.Components.Schemas.GetByName(schemaName) fmt.Printf("Schema: %s\n", schemaName) fmt.Printf(" Type: %s\n", schema.Type) fmt.Printf(" Description: %s\n", schema.Description) } } ``` -------------------------------- ### Set Document Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Sets or updates the configuration for reference handling and file access on an existing document. ```go func (d Document) SetConfiguration(configuration *datamodel.DocumentConfiguration) ``` -------------------------------- ### Parse Overlay Bytes to Document Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-overlay.md Use `NewOverlayDocument` to parse raw bytes into a high-level overlay document. This is the first step before applying an overlay. ```go func NewOverlayDocument(overlayBytes []byte) (*highoverlay.Overlay, error) ``` ```go overlayBytes := []byte ( overlaySpecVersion: 1.0.0 info: title: API Overlay patches: - target: $.info.description value: "Updated description" ) overlay, err := libopenapi.NewOverlayDocument(overlayBytes) if err != nil { panic(err) } ``` -------------------------------- ### Bundle Document Functions Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Bundles a Document model into bytes, with or without inline configuration. ```go func bundler.BundleDocument(model *v3.Document) ([]byte, error) ``` ```go func bundler.BundleDocumentWithConfig(model *v3.Document, bundleConfig *BundleInlineConfig) ([]byte, error) ``` -------------------------------- ### Bundle a Multi-File OpenAPI Specification Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Bundles a multi-file OpenAPI specification into a single, self-contained document using specified configuration. ```go import "github.com/pb33f/libopenapi/bundler" config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, BasePath: "/specs", } bundled, err := bundler.BundleBytes(specBytes, config) if err != nil { panic(err) } // bundled is now a single self-contained spec ``` -------------------------------- ### Render Document Inline (All Refs Resolved) Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Serialize the data model into YAML format with all references inlined. This produces a self-contained document. ```go bytes, err := model.Model.RenderInline() // Returns YAML with all references inlined ``` -------------------------------- ### Base External Documentation Structure Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Provides a reference to external documentation with a description and URL. ```go type base.ExternalDoc struct { Description string Url string } ``` -------------------------------- ### Document Interface Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md The entry point for all operations, representing a parsed OpenAPI specification. It provides methods to access version, rolodex, spec info, configuration, build models, render, and serialize the document. ```go type Document interface { GetVersion() string GetRolodex() *index.Rolodex GetSpecInfo() *datamodel.SpecInfo SetConfiguration(configuration *datamodel.DocumentConfiguration) GetConfiguration() *datamodel.DocumentConfiguration BuildV2Model() (*DocumentModel[v2high.Swagger], error) BuildV3Model() (*DocumentModel[v3high.Document], error) RenderAndReload() ([]byte, Document, *DocumentModel[v3high.Document], error) Render() ([]byte, error) Serialize() ([]byte, error) Release() } ``` -------------------------------- ### Parse and Build OpenAPI Document Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/README.md Parses OpenAPI specification bytes into a document and builds a V3 model. Remember to release the document and clear caches when done. ```go import "github.com/pb33f/libopenapi" // Parse spec doc, err := libopenapi.NewDocument(specBytes) if err != nil { panic(err) } // Build model model, err := doc.BuildV3Model() if err != nil { panic(err) } // Access endpoints for path := range model.Model.Paths.PathItems { pathItem := model.Model.Paths.PathItems[path] fmt.Printf("Path: %s\n", path) } // Clean up doc.Release() libopenapi.ClearAllCaches() ``` -------------------------------- ### Create New Document Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/configuration.md Creates a new DocumentConfiguration with default safe values. All references are disabled by default, and circular reference checks are enabled. ```go config := datamodel.NewDocumentConfiguration() config.AllowFileReferences = true config.BasePath = "/specs" doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) ``` -------------------------------- ### Accessing Schemas from Components Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Demonstrates how to access and iterate through named schemas defined within the Components object. ```go if model.Model.Components != nil && model.Model.Components.Schemas != nil { // Get all schema names (ordered) for schemaName := range model.Model.Components.Schemas.FromOldest() { schema := model.Model.Components.Schemas.GetByName(schemaName) fmt.Printf("Schema: %s\n", schemaName) } } ``` -------------------------------- ### Access AST Information from OpenAPI Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Shows how to access the Abstract Syntax Tree (AST) information from a libopenapi model, including line and column numbers for various elements. ```go // Get low-level document lowDoc := model.Model.GoLow() // Access line/column information fmt.Printf("Document version at line %d, column %d\n", lowDoc.Version.KeyNode.Line, lowDoc.Version.KeyNode.Column) // Get low-level path item lowPath := model.Model.Paths.PathItems["/pets"].GoLow() fmt.Printf("Path at line %d\n", lowPath.KeyNode.Line) // Get low-level schema lowSchema := model.Model.Components.Schemas.GetByName("Pet").GoLow() fmt.Printf("Pet schema at line %d\n", lowSchema.KeyNode.Line) ``` -------------------------------- ### Apply an Overlay to an OpenAPI Specification Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Applies an overlay to a target OpenAPI specification, returning the modified spec, the overlay document, and any warnings. ```go targetDoc, _ := libopenapi.NewDocument(targetBytes) result, err := libopenapi.ApplyOverlayFromBytes(targetDoc, overlayBytes) if err != nil { panic(err) } // result.Bytes contains the modified spec // result.OverlayDocument is a Document ready for model building // result.Warnings contains any non-fatal issues model, _ := result.OverlayDocument.BuildV3Model() ``` -------------------------------- ### Server Data Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Represents connection information to a target server. It includes the URL, a description, and any variables used in the URL. ```go type Server struct { Url string Description string Variables *OrderedMap // Key: variable name, Value: ServerVariable } ``` -------------------------------- ### Access SourceDescription Structure Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-arazzo.md Demonstrates how to access the details of SourceDescriptions, which specify how to locate and use referenced OpenAPI documents. Use this to understand where the workflow's API definitions are sourced from. ```go for _, source := range arazzo.SourceDescriptions { fmt.Printf("Source: %s\n", source.Name) fmt.Printf(" URL: %s\n", source.Url) } ``` -------------------------------- ### Bundle Bytes Functions Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Provides functions to bundle specification bytes with various configurations, including composed bundling and origin tracking. ```go func bundler.BundleBytes(bytes []byte, configuration *datamodel.DocumentConfiguration) ([]byte, error) ``` ```go func bundler.BundleBytesComposed(bytes []byte, configuration *datamodel.DocumentConfiguration, compositionConfig *BundleCompositionConfig) ([]byte, error) ``` ```go func bundler.BundleBytesComposedWithOrigins(bytes []byte, configuration *datamodel.DocumentConfiguration, compositionConfig *BundleCompositionConfig) (*BundleResult, error) ``` -------------------------------- ### Apply Overlay Functions Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Applies an overlay to a document, either from an existing overlay object or from bytes. Also supports applying overlays directly to spec bytes. ```go func ApplyOverlay(document Document, ov *highoverlay.Overlay) (*OverlayResult, error) ``` ```go func ApplyOverlayFromBytes(document Document, overlayBytes []byte) (*OverlayResult, error) ``` ```go func ApplyOverlayToSpecBytes(docBytes []byte, ov *highoverlay.Overlay) (*OverlayResult, error) ``` ```go func ApplyOverlayFromBytesToSpecBytes(docBytes, overlayBytes []byte) (*OverlayResult, error) ``` -------------------------------- ### Load and Integrate Arazzo with OpenAPI Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-arazzo.md Loads an OpenAPI document and an Arazzo workflow document, then iterates through workflow steps to match them with API operations defined in the OpenAPI model. Requires the OpenAPI and Arazzo documents as byte slices. ```go // Load OpenAPI spec openAPIBytes := []byte(...) doc, err := libopenapi.NewDocument(openAPIBytes) if err != nil { panic(err) } model, err := doc.BuildV3Model() if err != nil { panic(err) } // Load Arazzo workflow arazzoBytes := []byte(...) arazzo, err := libopenapi.NewArazzoDocument(arazzoBytes) if err != nil { panic(err) } // Match workflows with API operations for _, workflow := range arazzo.Workflows { for _, step := range workflow.Steps { // Find the operation in the model if model.Model.Paths != nil { for path, pathItem := range model.Model.Paths.PathItems { // Look for operations matching step.OperationId // This would require iterating through path item operations // and matching operationId } } } } ``` -------------------------------- ### Manage Memory with Document Release and Cache Clearing Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/INDEX.md Demonstrates memory management best practices for long-running processes. It involves releasing document resources and clearing caches between processing cycles to prevent memory leaks. ```go for _, spec := range specs { doc, _ := libopenapi.NewDocument(spec) model, _ := doc.BuildV3Model() processModel(model) doc.Release() libopenapi.ClearAllCaches() } ``` -------------------------------- ### Compare OpenAPI Documents Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/README.md Compares two OpenAPI documents to identify breaking and non-breaking changes. Useful for tracking API evolution. ```go changes, err := libopenapi.CompareDocuments(originalDoc, updatedDoc) if changes.Breaking > 0 { fmt.Printf("WARNING: %d breaking changes\n", changes.Breaking) } ``` -------------------------------- ### Access Tags Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Retrieves and prints tag names and descriptions from both global tags and operation-specific tags. ```go for _, tag := range model.Model.Tags { fmt.Printf("Tag: %s\n", tag.Name) fmt.Printf(" Description: %s\n", tag.Description) } // Tags in operations op := model.Model.Paths.PathItems["/pets"].Get if op.Tags != nil { for _, tag := range op.Tags { fmt.Printf("Operation tag: %s\n", tag) } } ``` -------------------------------- ### Base License Structure Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/types-reference.md Defines license information for an API, including name, identifier, and URL. ```go type base.License struct { Name string Identifier string // 3.1+ Url string } ``` -------------------------------- ### Create New OpenAPI Document Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Creates a new OpenAPI document from raw specification bytes. Does not automatically follow file or remote references. ```go func NewDocument(specByteArray []byte) (Document, error) ``` ```go import "github.com/pb33f/libopenapi" func main() { specBytes := []byte( `openapi: 3.0.0 info: title: Pet Store version: 1.0.0 paths: /pets: get: summary: List pets ` ) doc, err := libopenapi.NewDocument(specBytes) if err != nil { panic(err) } model, err := doc.BuildV3Model() if err != nil { panic(err) } } ``` -------------------------------- ### Load OpenAPI Document with Local File Configuration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Load an OpenAPI specification with configuration to allow local file references. The BasePath is set to the directory containing the spec. ```go config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, BasePath: "/path/to/specs", } doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) if err != nil { panic(err) } model, err := doc.BuildV3Model() ``` -------------------------------- ### Compare Two OpenAPI Specifications Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/usage-guide.md Compares two OpenAPI specification files and reports the number of breaking, non-breaking, added, and removed changes. ```go originalBytes, _ := os.ReadFile("api-v1.yaml") updatedBytes, _ := os.ReadFile("api-v2.yaml") original, _ := libopenapi.NewDocument(originalBytes) updated, _ := libopenapi.NewDocument(updatedBytes) changes, err := libopenapi.CompareDocuments(original, updated) if err != nil { panic(err) } fmt.Printf("Changes Summary:\n") fmt.Printf(" Breaking: %d\n", changes.Breaking) fmt.Printf(" Non-breaking: %d\n", changes.NonBreaking) fmt.Printf(" Added: %d\n", changes.Added) fmt.Printf(" Removed: %d\n", changes.Removed) ``` -------------------------------- ### Build V3 OpenAPI Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Builds a strongly-typed OpenAPI 3.x model. Supports various OpenAPI 3.x versions. Throws an error if the specification is not OpenAPI 3.x or has validation errors. ```go func (d Document) BuildV3Model() (*DocumentModel[v3high.Document], error) ``` ```go v3Model, err := doc.BuildV3Model() if err != nil { panic(err) } // Access paths for path, pathItem := range v3Model.Model.Paths.PathItems { fmt.Printf("Path: %s\n", path) } // Access components if v3Model.Model.Components != nil { for schemaName := range v3Model.Model.Components.Schemas.FromOldest() { fmt.Printf("Schema: %s\n", schemaName) } } ``` -------------------------------- ### NewDocumentWithConfiguration Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/api-reference-document.md Creates a new OpenAPI document with explicit configuration for reference handling. This allows fine-grained control over reference resolution. ```APIDOC ## NewDocumentWithConfiguration ### Description Creates a new OpenAPI document with explicit configuration for reference handling, allowing fine-grained control over whether file and remote references are resolved. ### Method `NewDocumentWithConfiguration` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | specByteArray | []byte | Yes | — | The complete OpenAPI/Swagger specification as YAML or JSON bytes | | configuration | *datamodel.DocumentConfiguration | No | — | Configuration controlling reference resolution, base URLs, and file access | ### Return Type `(Document, error)` Returns a Document with the specified configuration applied, or an error if parsing fails. ### Behavior Allows fine-grained control over whether file references (`AllowFileReferences`) and remote references (`AllowRemoteReferences`) are resolved during document loading. ### Example ```go config := &datamodel.DocumentConfiguration{ AllowFileReferences: true, AllowRemoteReferences: true, BaseURL: "file:///specs/", } doc, err := libopenapi.NewDocumentWithConfiguration(specBytes, config) if err != nil { panic(err) } ``` ``` -------------------------------- ### Parameter Data Model Source: https://github.com/pb33f/libopenapi/blob/main/_autodocs/data-model-overview.md Describes an operation parameter, including its name, location (query, header, path, cookie), description, and schema. ```go type Parameter struct { Name string In string // "query", "header", "path", "cookie" Description string Required bool Deprecated bool Schema *Schema Style string Explode *bool AllowReserved *bool AllowEmptyValue bool } ```