openapi

package
v1.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2025 License: MIT Imports: 33 Imported by: 0

README

OpenAPI

OpenAPI Parser

An API for working with OpenAPI documents including: read, walk, create, mutate, validate, and upgrade

OpenAPI Hub Built by Speakeasy Release Go Doc
Go Report Card Software License

Features

  • Full OpenAPI 3.0.x and 3.1.x Support: Parse and work with both OpenAPI 3.0.x and 3.1.x documents
  • Validation: Built-in validation against the OpenAPI Specification
  • Walking: Traverse all elements in an OpenAPI document with a powerful iterator pattern
  • Upgrading: Automatically upgrade OpenAPI 3.0.x documents to 3.1.1
  • Mutation: Modify OpenAPI documents programmatically
  • JSON Schema Support: Direct access to JSON Schema functionality
  • Reference Resolution: Resolve $ref references within documents
  • Circular Reference Handling: Proper handling of circular references in schemas
  • Extension Support: Full support for OpenAPI extensions (x-* fields)
  • Type Safety: Strongly typed Go structs for all OpenAPI elements

Supported OpenAPI Versions

  • OpenAPI 3.0.0 through 3.0.4
  • OpenAPI 3.1.0 through 3.1.1 (latest)

The package can automatically upgrade documents from 3.0.x to 3.1.1, handling the differences in specification between versions.

Read and parse an OpenAPI document from a file

This includes validation by default and shows how to access document properties.

ctx := context.Background()

r, err := os.Open("testdata/test.openapi.yaml")
if err != nil {
	panic(err)
}
defer r.Close()

doc, validationErrs, err := openapi.Unmarshal(ctx, r)
if err != nil {
	panic(err)
}

for _, err := range validationErrs {
	fmt.Println(err.Error())
}

fmt.Printf("OpenAPI Version: %s\n", doc.OpenAPI)
fmt.Printf("API Title: %s\n", doc.Info.Title)
fmt.Printf("API Version: %s\n", doc.Info.Version)

Work with JSON Schema directly

Shows how to unmarshal a JSONSchema from YAML or JSON and validate it manually.

ctx := context.Background()

schemaYAML := `
type: object
properties:
  id:
    type: integer
    format: int64
  name:
    type: string
    maxLength: 100
  email:
    type: string
    format: email
required:
  - id
  - name
  - email
`

// Unmarshal directly to a JSONSchema using marshaller.Unmarshal
var schema oas3.JSONSchema[oas3.Concrete]
validationErrs, err := marshaller.Unmarshal(ctx, bytes.NewReader([]byte(schemaYAML)), &schema)
if err != nil {
	panic(err)
}

additionalErrs := schema.Validate(ctx)
validationErrs = append(validationErrs, additionalErrs...)

if len(validationErrs) > 0 {
	for _, err := range validationErrs {
		fmt.Println("Validation error:", err.Error())
	}
}

if schema.IsLeft() {
	schemaObj := schema.GetLeft()
	fmt.Println("Schema Types:")
	for _, t := range schemaObj.GetType() {
		fmt.Printf("  %s\n", t)
	}
	fmt.Printf("Required Fields: %v\n", schemaObj.GetRequired())
	fmt.Printf("Number of Properties: %d\n", schemaObj.GetProperties().Len())
}

Marshal an OpenAPI document to a writer

Shows creating a simple document and outputting it as YAML.

ctx := context.Background()

doc := &openapi.OpenAPI{
	OpenAPI: openapi.Version,
	Info: openapi.Info{
		Title:   "Example API",
		Version: "1.0.0",
	},
	Paths: openapi.NewPaths(),
}

buf := bytes.NewBuffer([]byte{})

if err := openapi.Marshal(ctx, doc, buf); err != nil {
	panic(err)
}

fmt.Printf("%s", buf.String())

Marshal a JSONSchema directly

Shows creating a schema programmatically and outputting it as YAML.

ctx := context.Background()

properties := sequencedmap.New(
	sequencedmap.NewElem("id", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
		Type:   oas3.NewTypeFromString(oas3.SchemaTypeInteger),
		Format: pointer.From("int64"),
	})),
	sequencedmap.NewElem("name", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
		Type:      oas3.NewTypeFromString(oas3.SchemaTypeString),
		MaxLength: pointer.From(int64(100)),
	})),
)

schema := oas3.NewJSONSchemaFromSchema[oas3.Concrete](&oas3.Schema{
	Type:       oas3.NewTypeFromString(oas3.SchemaTypeObject),
	Properties: properties,
	Required:   []string{"id", "name"},
})

buf := bytes.NewBuffer([]byte{})

if err := marshaller.Marshal(ctx, schema, buf); err != nil {
	panic(err)
}

fmt.Printf("%s", buf.String())

Validate an OpenAPI document

Shows both automatic validation during unmarshaling and explicit validation.

ctx := context.Background()

f, err := os.Open("testdata/invalid.openapi.yaml")
if err != nil {
	panic(err)
}
defer f.Close()

doc, validationErrs, err := openapi.Unmarshal(ctx, f)
if err != nil {
	panic(err)
}

for _, err := range validationErrs {
	fmt.Printf("Validation error: %s\n", err.Error())
}

additionalErrs := doc.Validate(ctx)
for _, err := range additionalErrs {
	fmt.Printf("Additional validation error: %s\n", err.Error())
}

if len(validationErrs) == 0 && len(additionalErrs) == 0 {
	fmt.Println("Document is valid!")
}

Read and modify an OpenAPI document

Shows loading a document, making changes, and marshaling it back to YAML.

ctx := context.Background()

r, err := os.Open("testdata/simple.openapi.yaml")
if err != nil {
	panic(err)
}
defer r.Close()

doc, validationErrs, err := openapi.Unmarshal(ctx, r)
if err != nil {
	panic(err)
}

for _, err := range validationErrs {
	fmt.Println(err.Error())
}

doc.Info.Title = "Updated Simple API"
doc.Info.Description = pointer.From("This API has been updated with new description")

doc.Servers = append(doc.Servers, &openapi.Server{
	URL:         "https://api.updated.com/v1",
	Description: pointer.From("Updated server"),
})

buf := bytes.NewBuffer([]byte{})

if err := openapi.Marshal(ctx, doc, buf); err != nil {
	panic(err)
}

fmt.Println("Updated document:")
fmt.Println(buf.String())

Traverse an OpenAPI document using the iterator API

Shows how to match different types of objects and terminate the walk early.

ctx := context.Background()

f, err := os.Open("testdata/test.openapi.yaml")
if err != nil {
	panic(err)
}
defer f.Close()

doc, _, err := openapi.Unmarshal(ctx, f)
if err != nil {
	panic(err)
}

operationCount := 0

for item := range openapi.Walk(ctx, doc) {

	err := item.Match(openapi.Matcher{
		OpenAPI: func(o *openapi.OpenAPI) error {
			fmt.Printf("Found OpenAPI document: %s\n", o.Info.Title)
			return nil
		},
		Info: func(info *openapi.Info) error {
			fmt.Printf("Found Info: %s (version %s)\n", info.Title, info.Version)
			return nil
		},
		Operation: func(op *openapi.Operation) error {
			if op.OperationID != nil {
				fmt.Printf("Found Operation: %s\n", *op.OperationID)
			}
			operationCount++

			if operationCount >= 2 {
				return walk.ErrTerminate
			}
			return nil
		},
		Schema: func(schema *oas3.JSONSchema[oas3.Referenceable]) error {
			if schema.IsLeft() && schema.GetLeft().Type != nil {
				types := schema.GetLeft().GetType()
				if len(types) > 0 {
					fmt.Printf("Found Schema of type: %s\n", types[0])
				}
			}
			return nil
		},
	})
	if err != nil {
		if errors.Is(err, walk.ErrTerminate) {
			fmt.Println("Walk terminated early")
			break
		}
		fmt.Printf("Error during walk: %s\n", err.Error())
		break
	}
}

Resolve all references in an OpenAPI document

in a single operation, which is convenient as you can then use MustGetObject() and expect them to be resolved already.

ctx := context.Background()

absPath, err := filepath.Abs("testdata/resolve_test/main.yaml")
if err != nil {
	panic(err)
}

f, err := os.Open(absPath)
if err != nil {
	panic(err)
}
defer f.Close()

doc, validationErrs, err := openapi.Unmarshal(ctx, f)
if err != nil {
	panic(err)
}

if len(validationErrs) > 0 {
	for _, err := range validationErrs {
		fmt.Printf("Validation error: %s\n", err.Error())
	}
}

resolveValidationErrs, resolveErrs := doc.ResolveAllReferences(ctx, openapi.ResolveAllOptions{
	OpenAPILocation: absPath,
})

if resolveErrs != nil {
	fmt.Printf("Resolution error: %s\n", resolveErrs.Error())
	return
}

if len(resolveValidationErrs) > 0 {
	for _, err := range resolveValidationErrs {
		fmt.Printf("Resolution validation error: %s\n", err.Error())
	}
}

if doc.Paths != nil {
	for path, pathItem := range doc.Paths.All() {
		if pathItem.IsReference() && pathItem.IsResolved() {
			fmt.Printf("Path %s is a resolved reference\n", path)
		}
	}
}

fmt.Println("All references resolved successfully!")

Resolve references individually

as you encounter them during document traversal using the model API instead of the walk API.

ctx := context.Background()

absPath, err := filepath.Abs("testdata/resolve_test/main.yaml")
if err != nil {
	panic(err)
}

f, err := os.Open(absPath)
if err != nil {
	panic(err)
}
defer f.Close()

doc, _, err := openapi.Unmarshal(ctx, f)
if err != nil {
	panic(err)
}

resolveOpts := openapi.ResolveOptions{
	TargetLocation: absPath,
	RootDocument:   doc,
}

if doc.Paths != nil {
	for path, pathItem := range doc.Paths.All() {
		fmt.Printf("Processing path: %s\n", path)

		if pathItem.IsReference() && !pathItem.IsResolved() {
			fmt.Printf("  Resolving path item reference: %s\n", pathItem.GetReference())
			_, err := pathItem.Resolve(ctx, resolveOpts)
			if err != nil {
				fmt.Printf("  Failed to resolve path item: %v\n", err)
				continue
			}
		}

		pathItemObj := pathItem.GetObject()
		if pathItemObj == nil {
			continue
		}

		for i, param := range pathItemObj.Parameters {
			if param.IsReference() && !param.IsResolved() {
				fmt.Printf("  Resolving parameter reference [%d]: %s\n", i, param.GetReference())
				_, err := param.Resolve(ctx, resolveOpts)
				if err != nil {
					fmt.Printf("  Failed to resolve parameter: %v\n", err)
					continue
				}
				if paramObj := param.GetObject(); paramObj != nil {
					fmt.Printf("  Parameter resolved: %s\n", paramObj.Name)
				}
			}
		}

		for method, operation := range pathItemObj.All() {
			fmt.Printf("  Processing operation: %s\n", method)

			for i, param := range operation.Parameters {
				if param.IsReference() && !param.IsResolved() {
					fmt.Printf("    Resolving operation parameter reference [%d]: %s\n", i, param.GetReference())
					_, err := param.Resolve(ctx, resolveOpts)
					if err != nil {
						fmt.Printf("    Failed to resolve parameter: %v\n", err)
						continue
					}
					if paramObj := param.GetObject(); paramObj != nil {
						fmt.Printf("    Parameter resolved: %s\n", paramObj.Name)
					}
				}
			}

			if operation.Responses != nil {
				for statusCode, response := range operation.Responses.All() {
					if response.IsReference() && !response.IsResolved() {
						fmt.Printf("    Resolving response reference [%s]: %s\n", statusCode, response.GetReference())
						_, err := response.Resolve(ctx, resolveOpts)
						if err != nil {
							fmt.Printf("    Failed to resolve response: %v\n", err)
							continue
						}
						if respObj := response.GetObject(); respObj != nil {
							fmt.Printf("    Response resolved: %s\n", respObj.Description)
						}
					}
				}
			}
		}
	}
}

fmt.Println("References resolved as encountered!")

Create an OpenAPI document from scratch

Shows building a complete document with paths, operations, and responses programmatically.

ctx := context.Background()

paths := openapi.NewPaths()

pathItem := openapi.NewPathItem()
pathItem.Set(openapi.HTTPMethodGet, &openapi.Operation{
	OperationID: pointer.From("getUsers"),
	Summary:     pointer.From("Get all users"),
	Responses:   openapi.NewResponses(),
})

response200 := &openapi.ReferencedResponse{
	Object: &openapi.Response{
		Description: "Successful response",
	},
}
pathItem.Get().Responses.Set("200", response200)

referencedPathItem := &openapi.ReferencedPathItem{
	Object: pathItem,
}
paths.Set("/users", referencedPathItem)

doc := &openapi.OpenAPI{
	OpenAPI: openapi.Version,
	Info: openapi.Info{
		Title:       "My API",
		Description: pointer.From("A sample API created programmatically"),
		Version:     "1.0.0",
	},
	Servers: []*openapi.Server{
		{
			URL:         "https://api.example.com/v1",
			Description: pointer.From("Production server"),
		},
	},
	Paths: paths,
}

buf := bytes.NewBuffer([]byte{})

err := openapi.Marshal(ctx, doc, buf)
if err != nil {
	panic(err)
}

fmt.Printf("%s", buf.String())

Work with reusable components

in an OpenAPI document, including schemas, parameters, responses, etc.

ctx := context.Background()

schemas := sequencedmap.New(
	sequencedmap.NewElem("User", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
		Type: oas3.NewTypeFromString(oas3.SchemaTypeObject),
		Properties: sequencedmap.New(
			sequencedmap.NewElem("id", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
				Type: oas3.NewTypeFromString(oas3.SchemaTypeInteger),
			})),
			sequencedmap.NewElem("name", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
				Type: oas3.NewTypeFromString(oas3.SchemaTypeString),
			})),
		),
		Required: []string{"id", "name"},
	})),
)

parameters := sequencedmap.New(
	sequencedmap.NewElem("UserIdParam", &openapi.ReferencedParameter{
		Object: &openapi.Parameter{
			Name:     "userId",
			In:       "path",
			Required: pointer.From(true),
			Schema: oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
				Type: oas3.NewTypeFromString(oas3.SchemaTypeInteger),
			}),
		},
	}),
)

paths := openapi.NewPaths()
pathItem := openapi.NewPathItem()

ref := references.Reference("#/components/parameters/UserIdParam")
pathItem.Parameters = []*openapi.ReferencedParameter{
	{
		Reference: &ref,
	},
}

pathItem.Set(openapi.HTTPMethodGet, &openapi.Operation{
	OperationID: pointer.From("getUser"),
	Responses:   openapi.NewResponses(),
})

response200 := &openapi.ReferencedResponse{
	Object: &openapi.Response{
		Description: "User details",
		Content: sequencedmap.New(
			sequencedmap.NewElem("application/json", &openapi.MediaType{
				Schema: oas3.NewJSONSchemaFromReference("#/components/schemas/User"),
			}),
		),
	},
}
pathItem.Get().Responses.Set("200", response200)

paths.Set("/users/{userId}", &openapi.ReferencedPathItem{
	Object: pathItem,
})

doc := &openapi.OpenAPI{
	OpenAPI: openapi.Version,
	Info: openapi.Info{
		Title:   "API with Components",
		Version: "1.0.0",
	},
	Components: &openapi.Components{
		Schemas:    schemas,
		Parameters: parameters,
	},
	Paths: paths,
}

if doc.Components != nil && doc.Components.Schemas != nil {
	for name, schema := range doc.Components.Schemas.All() {
		fmt.Printf("Found schema component: %s\n", name)
		if schema.IsLeft() && schema.GetLeft().Type != nil {
			types := schema.GetLeft().GetType()
			if len(types) > 0 {
				fmt.Printf("  Type: %s\n", types[0])
			}
		}
	}
}

buf := bytes.NewBuffer([]byte{})
if err := openapi.Marshal(ctx, doc, buf); err != nil {
	panic(err)
}

fmt.Printf("Document with components:\n%s", buf.String())

Inline all references in a JSON Schema

creating a self-contained schema that doesn't depend on external definitions.

ctx := context.Background()

schemaJSON := `{
  "type": "object",
  "properties": {
    "user": {"$ref": "#/$defs/User"},
    "users": {
      "type": "array",
      "items": {"$ref": "#/$defs/User"}
    }
  },
  "$defs": {
    "User": {
      "type": "object",
      "properties": {
        "id": {"type": "integer"},
        "name": {"type": "string"},
        "address": {"$ref": "#/$defs/Address"}
      },
      "required": ["id", "name"]
    },
    "Address": {
      "type": "object",
      "properties": {
        "street": {"type": "string"},
        "city": {"type": "string"}
      },
      "required": ["street", "city"]
    }
  }
}`

// Unmarshal the JSON Schema
var schema oas3.JSONSchema[oas3.Referenceable]
validationErrs, err := marshaller.Unmarshal(ctx, bytes.NewReader([]byte(schemaJSON)), &schema)
if err != nil {
	panic(err)
}
if len(validationErrs) > 0 {
	for _, err := range validationErrs {
		fmt.Printf("Validation error: %s\n", err.Error())
	}
}

opts := oas3.InlineOptions{
	ResolveOptions: oas3.ResolveOptions{
		TargetLocation: "schema.json",
		RootDocument:   &schema,
	},
	RemoveUnusedDefs: true,
}

inlinedSchema, err := oas3.Inline(ctx, &schema, opts)
if err != nil {
	panic(err)
}

fmt.Println("After inlining:")
buf := bytes.NewBuffer([]byte{})
ctx = yml.ContextWithConfig(ctx, schema.GetCore().Config)
if err := marshaller.Marshal(ctx, inlinedSchema, buf); err != nil {
	panic(err)
}
fmt.Printf("%s", buf.String())

Upgrade an OpenAPI document from 3.0.x to 3.1.1

Shows the automatic conversion of nullable fields, examples, and other version differences.

ctx := context.Background()

openAPIYAML := `openapi: 3.0.3
info:
  title: Legacy API
  version: 1.0.0
  description: An API that needs upgrading from 3.0.3 to 3.1.1
paths:
  /users:
    get:
      summary: Get users
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
          nullable: true
          example: "John Doe"
        email:
          type: string
          format: email
          exclusiveMaximum: true
          maximum: 100
      required:
        - id`

doc, _, err := openapi.Unmarshal(ctx, bytes.NewReader([]byte(openAPIYAML)))
if err != nil {
	panic(err)
}

upgraded, err := openapi.Upgrade(ctx, doc)
if err != nil {
	panic(err)
}
if !upgraded {
	panic("upgrade should have been performed")
}

fmt.Printf("Upgraded OpenAPI Version: %s\n", doc.OpenAPI)

fmt.Println("\nAfter upgrade:")
buf := bytes.NewBuffer([]byte{})
if err := openapi.Marshal(ctx, doc, buf); err != nil {
	panic(err)
}
fmt.Printf("%s", buf.String())

Contributing

This repository is maintained by Speakeasy, but we welcome and encourage contributions from the community to help improve its capabilities and stability.

How to Contribute

  1. Open Issues: Found a bug or have a feature suggestion? Open an issue to describe what you'd like to see changed.

  2. Pull Requests: We welcome pull requests! If you'd like to contribute code:

    • Fork the repository
    • Create a new branch for your feature/fix
    • Submit a PR with a clear description of the changes and any related issues
  3. Feedback: Share your experience using the packages or suggest improvements.

All contributions, whether they're bug reports, feature requests, or code changes, help make this project better for everyone.

Please ensure your contributions adhere to our coding standards and include appropriate tests where applicable.

Documentation

Overview

Example (Creating)

Example_creating demonstrates how to create an OpenAPI document from scratch. Shows building a complete document with paths, operations, and responses programmatically.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/openapi"
	"github.com/speakeasy-api/openapi/pointer"
)

func main() {
	ctx := context.Background()

	// Create a new OpenAPI document
	paths := openapi.NewPaths()

	// Create a path item with a GET operation
	pathItem := openapi.NewPathItem()
	pathItem.Set(openapi.HTTPMethodGet, &openapi.Operation{
		OperationID: pointer.From("getUsers"),
		Summary:     pointer.From("Get all users"),
		Responses:   openapi.NewResponses(),
	})

	// Add a 200 response
	response200 := &openapi.ReferencedResponse{
		Object: &openapi.Response{
			Description: "Successful response",
		},
	}
	pathItem.Get().Responses.Set("200", response200)

	// Add the path item to paths
	referencedPathItem := &openapi.ReferencedPathItem{
		Object: pathItem,
	}
	paths.Set("/users", referencedPathItem)

	doc := &openapi.OpenAPI{
		OpenAPI: openapi.Version,
		Info: openapi.Info{
			Title:       "My API",
			Description: pointer.From("A sample API created programmatically"),
			Version:     "1.0.0",
		},
		Servers: []*openapi.Server{
			{
				URL:         "https://api.example.com/v1",
				Description: pointer.From("Production server"),
			},
		},
		Paths: paths,
	}

	buf := bytes.NewBuffer([]byte{})

	err := openapi.Marshal(ctx, doc, buf)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s", buf.String())
}
Output:

openapi: 3.1.1
info:
  title: My API
  version: 1.0.0
  description: A sample API created programmatically
servers:
  - url: https://api.example.com/v1
    description: Production server
paths:
  /users:
    get:
      operationId: getUsers
      summary: Get all users
      responses:
        "200":
          description: Successful response
Example (InliningSchema)

Example_inliningSchema demonstrates how to inline all references in a JSON Schema creating a self-contained schema that doesn't depend on external definitions.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/jsonschema/oas3"
	"github.com/speakeasy-api/openapi/marshaller"
	"github.com/speakeasy-api/openapi/yml"
)

func main() {
	ctx := context.Background()

	// JSON Schema with references that will be inlined
	schemaJSON := `{
  "type": "object",
  "properties": {
    "user": {"$ref": "#/$defs/User"},
    "users": {
      "type": "array",
      "items": {"$ref": "#/$defs/User"}
    }
  },
  "$defs": {
    "User": {
      "type": "object",
      "properties": {
        "id": {"type": "integer"},
        "name": {"type": "string"},
        "address": {"$ref": "#/$defs/Address"}
      },
      "required": ["id", "name"]
    },
    "Address": {
      "type": "object",
      "properties": {
        "street": {"type": "string"},
        "city": {"type": "string"}
      },
      "required": ["street", "city"]
    }
  }
}`

	// Unmarshal the JSON Schema
	var schema oas3.JSONSchema[oas3.Referenceable]
	validationErrs, err := marshaller.Unmarshal(ctx, bytes.NewReader([]byte(schemaJSON)), &schema)
	if err != nil {
		panic(err)
	}
	if len(validationErrs) > 0 {
		for _, err := range validationErrs {
			fmt.Printf("Validation error: %s\n", err.Error())
		}
	}

	// Configure inlining options
	opts := oas3.InlineOptions{
		ResolveOptions: oas3.ResolveOptions{
			TargetLocation: "schema.json",
			RootDocument:   &schema,
		},
		RemoveUnusedDefs: true, // Clean up unused definitions after inlining
	}

	// Inline all references
	inlinedSchema, err := oas3.Inline(ctx, &schema, opts)
	if err != nil {
		panic(err)
	}

	fmt.Println("After inlining:")
	buf := bytes.NewBuffer([]byte{})
	ctx = yml.ContextWithConfig(ctx, schema.GetCore().Config) // Use the same config as the original schema
	if err := marshaller.Marshal(ctx, inlinedSchema, buf); err != nil {
		panic(err)
	}
	fmt.Printf("%s", buf.String())
}
Output:

After inlining:
{
  "type": "object",
  "properties": {
    "user": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "name": {
          "type": "string"
        },
        "address": {
          "type": "object",
          "properties": {
            "street": {
              "type": "string"
            },
            "city": {
              "type": "string"
            }
          },
          "required": [
            "street",
            "city"
          ]
        }
      },
      "required": [
        "id",
        "name"
      ]
    },
    "users": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "address": {
            "type": "object",
            "properties": {
              "street": {
                "type": "string"
              },
              "city": {
                "type": "string"
              }
            },
            "required": [
              "street",
              "city"
            ]
          }
        },
        "required": [
          "id",
          "name"
        ]
      }
    }
  }
}
Example (Marshaling)

Example_marshaling demonstrates how to marshal an OpenAPI document to a writer. Shows creating a simple document and outputting it as YAML.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/openapi"
)

func main() {
	ctx := context.Background()

	// Create a simple OpenAPI document
	doc := &openapi.OpenAPI{
		OpenAPI: openapi.Version,
		Info: openapi.Info{
			Title:   "Example API",
			Version: "1.0.0",
		},
		Paths: openapi.NewPaths(),
	}

	buf := bytes.NewBuffer([]byte{})

	// Marshal the document to a writer
	if err := openapi.Marshal(ctx, doc, buf); err != nil {
		panic(err)
	}

	fmt.Printf("%s", buf.String())
}
Output:

openapi: 3.1.1
info:
  title: Example API
  version: 1.0.0
paths: {}
Example (MarshalingJSONSchema)

Example_marshalingJSONSchema demonstrates how to marshal a JSONSchema directly. Shows creating a schema programmatically and outputting it as YAML.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/jsonschema/oas3"
	"github.com/speakeasy-api/openapi/marshaller"
	"github.com/speakeasy-api/openapi/pointer"
	"github.com/speakeasy-api/openapi/sequencedmap"
)

func main() {
	ctx := context.Background()

	// Create a JSONSchema programmatically
	properties := sequencedmap.New(
		sequencedmap.NewElem("id", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
			Type:   oas3.NewTypeFromString(oas3.SchemaTypeInteger),
			Format: pointer.From("int64"),
		})),
		sequencedmap.NewElem("name", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
			Type:      oas3.NewTypeFromString(oas3.SchemaTypeString),
			MaxLength: pointer.From(int64(100)),
		})),
	)

	schema := oas3.NewJSONSchemaFromSchema[oas3.Concrete](&oas3.Schema{
		Type:       oas3.NewTypeFromString(oas3.SchemaTypeObject),
		Properties: properties,
		Required:   []string{"id", "name"},
	})

	buf := bytes.NewBuffer([]byte{})

	// Marshal the schema using marshaller.Marshal
	if err := marshaller.Marshal(ctx, schema, buf); err != nil {
		panic(err)
	}

	fmt.Printf("%s", buf.String())
}
Output:

type: object
properties:
  id:
    type: integer
    format: int64
  name:
    type: string
    maxLength: 100
required:
  - id
  - name
Example (Mutating)

Example_mutating demonstrates how to read and modify an OpenAPI document. Shows loading a document, making changes, and marshaling it back to YAML.

package main

import (
	"bytes"
	"context"
	"fmt"
	"os"

	"github.com/speakeasy-api/openapi/openapi"
	"github.com/speakeasy-api/openapi/pointer"
)

func main() {
	ctx := context.Background()

	r, err := os.Open("testdata/simple.openapi.yaml")
	if err != nil {
		panic(err)
	}
	defer r.Close()

	// Unmarshal the OpenAPI document
	doc, validationErrs, err := openapi.Unmarshal(ctx, r)
	if err != nil {
		panic(err)
	}

	// Print any validation errors
	for _, err := range validationErrs {
		fmt.Println(err.Error())
	}

	// Mutate the document by modifying the returned OpenAPI object
	doc.Info.Title = "Updated Simple API"
	doc.Info.Description = pointer.From("This API has been updated with new description")

	// Add a new server
	doc.Servers = append(doc.Servers, &openapi.Server{
		URL:         "https://api.updated.com/v1",
		Description: pointer.From("Updated server"),
	})

	buf := bytes.NewBuffer([]byte{})

	// Marshal the updated document
	if err := openapi.Marshal(ctx, doc, buf); err != nil {
		panic(err)
	}

	fmt.Println("Updated document:")
	fmt.Println(buf.String())
}
Output:

Updated document:
openapi: 3.1.1
info:
  title: Updated Simple API
  description: This API has been updated with new description
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
    description: Main server
  - url: https://api.updated.com/v1
    description: Updated server
paths:
  /users:
    get:
      operationId: getUsers
      summary: Get all users
      responses:
        "200":
          description: List of users
Example (Reading)

Example_reading demonstrates how to read and parse an OpenAPI document from a file. This includes validation by default and shows how to access document properties.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/speakeasy-api/openapi/openapi"
)

func main() {
	ctx := context.Background()

	r, err := os.Open("testdata/test.openapi.yaml")
	if err != nil {
		panic(err)
	}
	defer r.Close()

	// Unmarshal the OpenAPI document which will also validate it against the OpenAPI Specification
	doc, validationErrs, err := openapi.Unmarshal(ctx, r /*, openapi.WithSkipValidation()*/) // Optionally skip validation
	if err != nil {
		panic(err)
	}

	// Validation errors are returned separately from any errors that block the document from being unmarshalled
	// allowing an invalid document to be mutated and fixed before being marshalled again
	for _, err := range validationErrs {
		fmt.Println(err.Error())
	}

	fmt.Printf("OpenAPI Version: %s\n", doc.OpenAPI)
	fmt.Printf("API Title: %s\n", doc.Info.Title)
	fmt.Printf("API Version: %s\n", doc.Info.Version)
}
Output:

OpenAPI Version: 3.1.1
API Title: Test OpenAPI Document
API Version: 1.0.0
Example (ResolvingAllReferences)

Example_resolvingAllReferences demonstrates how to resolve all references in an OpenAPI document in a single operation, which is convenient as you can then use MustGetObject() and expect them to be resolved already.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/speakeasy-api/openapi/openapi"
)

func main() {
	ctx := context.Background()

	absPath, err := filepath.Abs("testdata/resolve_test/main.yaml")
	if err != nil {
		panic(err)
	}

	f, err := os.Open(absPath)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// Unmarshal the document
	doc, validationErrs, err := openapi.Unmarshal(ctx, f)
	if err != nil {
		panic(err)
	}

	if len(validationErrs) > 0 {
		for _, err := range validationErrs {
			fmt.Printf("Validation error: %s\n", err.Error())
		}
	}

	// Resolve all references in the document
	resolveValidationErrs, resolveErrs := doc.ResolveAllReferences(ctx, openapi.ResolveAllOptions{
		OpenAPILocation: absPath,
	})

	if resolveErrs != nil {
		fmt.Printf("Resolution error: %s\n", resolveErrs.Error())
		return
	}

	if len(resolveValidationErrs) > 0 {
		for _, err := range resolveValidationErrs {
			fmt.Printf("Resolution validation error: %s\n", err.Error())
		}
	}

	// Now all references are resolved and can be accessed directly
	if doc.Paths != nil {
		for path, pathItem := range doc.Paths.All() {
			if pathItem.IsReference() && pathItem.IsResolved() {
				fmt.Printf("Path %s is a resolved reference\n", path)
			}
		}
	}

	fmt.Println("All references resolved successfully!")
}
Output:

All references resolved successfully!
Example (ResolvingReferencesAsYouGo)

Example_resolvingReferencesAsYouGo demonstrates how to resolve references individually as you encounter them during document traversal using the model API instead of the walk API.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/speakeasy-api/openapi/openapi"
)

func main() {
	ctx := context.Background()

	absPath, err := filepath.Abs("testdata/resolve_test/main.yaml")
	if err != nil {
		panic(err)
	}

	f, err := os.Open(absPath)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// Unmarshal the document
	doc, _, err := openapi.Unmarshal(ctx, f)
	if err != nil {
		panic(err)
	}

	resolveOpts := openapi.ResolveOptions{
		TargetLocation: absPath,
		RootDocument:   doc,
	}

	// Walk through the document using the model API and resolve references as we encounter them
	if doc.Paths != nil {
		for path, pathItem := range doc.Paths.All() {
			fmt.Printf("Processing path: %s\n", path)

			if pathItem.IsReference() && !pathItem.IsResolved() {
				fmt.Printf("  Resolving path item reference: %s\n", pathItem.GetReference())
				_, err := pathItem.Resolve(ctx, resolveOpts)
				if err != nil {
					fmt.Printf("  Failed to resolve path item: %v\n", err)
					continue
				}
			}

			// Get the resolved path item
			pathItemObj := pathItem.GetObject()
			if pathItemObj == nil {
				continue
			}

			// Check parameters
			for i, param := range pathItemObj.Parameters {
				if param.IsReference() && !param.IsResolved() {
					fmt.Printf("  Resolving parameter reference [%d]: %s\n", i, param.GetReference())
					_, err := param.Resolve(ctx, resolveOpts)
					if err != nil {
						fmt.Printf("  Failed to resolve parameter: %v\n", err)
						continue
					}
					if paramObj := param.GetObject(); paramObj != nil {
						fmt.Printf("  Parameter resolved: %s\n", paramObj.Name)
					}
				}
			}

			// Check operations
			for method, operation := range pathItemObj.All() {
				fmt.Printf("  Processing operation: %s\n", method)

				// Check operation parameters
				for i, param := range operation.Parameters {
					if param.IsReference() && !param.IsResolved() {
						fmt.Printf("    Resolving operation parameter reference [%d]: %s\n", i, param.GetReference())
						_, err := param.Resolve(ctx, resolveOpts)
						if err != nil {
							fmt.Printf("    Failed to resolve parameter: %v\n", err)
							continue
						}
						if paramObj := param.GetObject(); paramObj != nil {
							fmt.Printf("    Parameter resolved: %s\n", paramObj.Name)
						}
					}
				}

				// Check responses
				if operation.Responses != nil {
					for statusCode, response := range operation.Responses.All() {
						if response.IsReference() && !response.IsResolved() {
							fmt.Printf("    Resolving response reference [%s]: %s\n", statusCode, response.GetReference())
							_, err := response.Resolve(ctx, resolveOpts)
							if err != nil {
								fmt.Printf("    Failed to resolve response: %v\n", err)
								continue
							}
							if respObj := response.GetObject(); respObj != nil {
								fmt.Printf("    Response resolved: %s\n", respObj.Description)
							}
						}
					}
				}
			}
		}
	}

	fmt.Println("References resolved as encountered!")
}
Output:

Processing path: /users/{userId}
  Processing operation: get
    Resolving operation parameter reference [0]: #/components/parameters/testParamRef
    Parameter resolved: userId
    Resolving response reference [200]: #/components/responses/testResponseRef
    Response resolved: User response
Processing path: /users
  Processing operation: post
References resolved as encountered!
Example (Upgrading)

Example_upgrading demonstrates how to upgrade an OpenAPI document from 3.0.x to 3.1.1. Shows the automatic conversion of nullable fields, examples, and other version differences.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/openapi"
)

func main() {
	ctx := context.Background()

	// OpenAPI 3.0.3 document with features that need upgrading
	openAPIYAML := `openapi: 3.0.3
info:
  title: Legacy API
  version: 1.0.0
  description: An API that needs upgrading from 3.0.3 to 3.1.1
paths:
  /users:
    get:
      summary: Get users
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
          nullable: true
          example: "John Doe"
        email:
          type: string
          format: email
          exclusiveMaximum: true
          maximum: 100
      required:
        - id`

	// Unmarshal the OpenAPI document
	doc, _, err := openapi.Unmarshal(ctx, bytes.NewReader([]byte(openAPIYAML)))
	if err != nil {
		panic(err)
	}

	// Upgrade the document to the latest version
	upgraded, err := openapi.Upgrade(ctx, doc)
	if err != nil {
		panic(err)
	}
	if !upgraded {
		panic("upgrade should have been performed")
	}

	fmt.Printf("Upgraded OpenAPI Version: %s\n", doc.OpenAPI)

	// Marshal the upgraded document
	fmt.Println("\nAfter upgrade:")
	buf := bytes.NewBuffer([]byte{})
	if err := openapi.Marshal(ctx, doc, buf); err != nil {
		panic(err)
	}
	fmt.Printf("%s", buf.String())
}
Output:

Upgraded OpenAPI Version: 3.1.1

After upgrade:
openapi: 3.1.1
info:
  title: Legacy API
  version: 1.0.0
  description: An API that needs upgrading from 3.0.3 to 3.1.1
paths:
  /users:
    get:
      summary: Get users
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type:
            - string
            - "null"
          examples:
            - "John Doe"
        email:
          type: string
          format: email
          exclusiveMaximum: 100
      required:
        - id
Example (Validating)

Example_validating demonstrates how to validate an OpenAPI document. Shows both automatic validation during unmarshaling and explicit validation.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/speakeasy-api/openapi/openapi"
)

func main() {
	ctx := context.Background()

	f, err := os.Open("testdata/invalid.openapi.yaml")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// Unmarshal with validation (default behavior)
	doc, validationErrs, err := openapi.Unmarshal(ctx, f)
	if err != nil {
		panic(err)
	}

	// Print any validation errors
	for _, err := range validationErrs {
		fmt.Printf("Validation error: %s\n", err.Error())
	}

	// You can also validate explicitly after making changes
	additionalErrs := doc.Validate(ctx)
	for _, err := range additionalErrs {
		fmt.Printf("Additional validation error: %s\n", err.Error())
	}

	if len(validationErrs) == 0 && len(additionalErrs) == 0 {
		fmt.Println("Document is valid!")
	}
}
Output:

Validation error: [3:3] info field version is missing
Validation error: [18:30] response.content expected object, got scalar
Validation error: [31:25] schema field properties.name.type value must be one of 'array', 'boolean', 'integer', 'null', 'number', 'object', 'string'
Validation error: [31:25] schema field properties.name.type got string, want array
Additional validation error: [31:25] schema field properties.name.type value must be one of 'array', 'boolean', 'integer', 'null', 'number', 'object', 'string'
Additional validation error: [31:25] schema field properties.name.type got string, want array
Example (Walking)

Example_walking demonstrates how to traverse an OpenAPI document using the iterator API. Shows how to match different types of objects and terminate the walk early.

package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/speakeasy-api/openapi/jsonschema/oas3"
	"github.com/speakeasy-api/openapi/openapi"
	"github.com/speakeasy-api/openapi/walk"
)

func main() {
	ctx := context.Background()

	f, err := os.Open("testdata/test.openapi.yaml")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	doc, _, err := openapi.Unmarshal(ctx, f)
	if err != nil {
		panic(err)
	}

	operationCount := 0

	// Walk through the document using the iterator API
	for item := range openapi.Walk(ctx, doc) {
		// Use the matcher to handle different types of objects
		err := item.Match(openapi.Matcher{
			OpenAPI: func(o *openapi.OpenAPI) error {
				fmt.Printf("Found OpenAPI document: %s\n", o.Info.Title)
				return nil
			},
			Info: func(info *openapi.Info) error {
				fmt.Printf("Found Info: %s (version %s)\n", info.Title, info.Version)
				return nil
			},
			Operation: func(op *openapi.Operation) error {
				if op.OperationID != nil {
					fmt.Printf("Found Operation: %s\n", *op.OperationID)
				}
				operationCount++
				// Terminate after finding 2 operations
				if operationCount >= 2 {
					return walk.ErrTerminate
				}
				return nil
			},
			Schema: func(schema *oas3.JSONSchema[oas3.Referenceable]) error {
				if schema.IsLeft() && schema.GetLeft().Type != nil {
					types := schema.GetLeft().GetType()
					if len(types) > 0 {
						fmt.Printf("Found Schema of type: %s\n", types[0])
					}
				}
				return nil
			},
		})
		if err != nil {
			if errors.Is(err, walk.ErrTerminate) {
				fmt.Println("Walk terminated early")
				break
			}
			fmt.Printf("Error during walk: %s\n", err.Error())
			break
		}
	}
}
Output:

Found OpenAPI document: Test OpenAPI Document
Found Info: Test OpenAPI Document (version 1.0.0)
Found Schema of type: string
Found Operation: test
Found Schema of type: integer
Found Operation: updateUser
Walk terminated early
Example (WorkingWithComponents)

Example_workingWithComponents demonstrates how to work with reusable components in an OpenAPI document, including schemas, parameters, responses, etc.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/jsonschema/oas3"
	"github.com/speakeasy-api/openapi/openapi"
	"github.com/speakeasy-api/openapi/pointer"
	"github.com/speakeasy-api/openapi/references"
	"github.com/speakeasy-api/openapi/sequencedmap"
)

func main() {
	ctx := context.Background()

	// Create schema components
	schemas := sequencedmap.New(
		sequencedmap.NewElem("User", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
			Type: oas3.NewTypeFromString(oas3.SchemaTypeObject),
			Properties: sequencedmap.New(
				sequencedmap.NewElem("id", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
					Type: oas3.NewTypeFromString(oas3.SchemaTypeInteger),
				})),
				sequencedmap.NewElem("name", oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
					Type: oas3.NewTypeFromString(oas3.SchemaTypeString),
				})),
			),
			Required: []string{"id", "name"},
		})),
	)

	// Create parameter components
	parameters := sequencedmap.New(
		sequencedmap.NewElem("UserIdParam", &openapi.ReferencedParameter{
			Object: &openapi.Parameter{
				Name:     "userId",
				In:       "path",
				Required: pointer.From(true),
				Schema: oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{
					Type: oas3.NewTypeFromString(oas3.SchemaTypeInteger),
				}),
			},
		}),
	)

	// Create paths that use the components
	paths := openapi.NewPaths()
	pathItem := openapi.NewPathItem()

	// Add parameter reference
	ref := references.Reference("#/components/parameters/UserIdParam")
	pathItem.Parameters = []*openapi.ReferencedParameter{
		{
			Reference: &ref,
		},
	}

	// Add GET operation
	pathItem.Set(openapi.HTTPMethodGet, &openapi.Operation{
		OperationID: pointer.From("getUser"),
		Responses:   openapi.NewResponses(),
	})

	// Add response with schema reference
	response200 := &openapi.ReferencedResponse{
		Object: &openapi.Response{
			Description: "User details",
			Content: sequencedmap.New(
				sequencedmap.NewElem("application/json", &openapi.MediaType{
					Schema: oas3.NewJSONSchemaFromReference("#/components/schemas/User"),
				}),
			),
		},
	}
	pathItem.Get().Responses.Set("200", response200)

	paths.Set("/users/{userId}", &openapi.ReferencedPathItem{
		Object: pathItem,
	})

	// Create the OpenAPI document with components
	doc := &openapi.OpenAPI{
		OpenAPI: openapi.Version,
		Info: openapi.Info{
			Title:   "API with Components",
			Version: "1.0.0",
		},
		Components: &openapi.Components{
			Schemas:    schemas,
			Parameters: parameters,
		},
		Paths: paths,
	}

	// Access components
	if doc.Components != nil && doc.Components.Schemas != nil {
		for name, schema := range doc.Components.Schemas.All() {
			fmt.Printf("Found schema component: %s\n", name)
			if schema.IsLeft() && schema.GetLeft().Type != nil {
				types := schema.GetLeft().GetType()
				if len(types) > 0 {
					fmt.Printf("  Type: %s\n", types[0])
				}
			}
		}
	}

	buf := bytes.NewBuffer([]byte{})
	if err := openapi.Marshal(ctx, doc, buf); err != nil {
		panic(err)
	}

	fmt.Printf("Document with components:\n%s", buf.String())
}
Output:

Found schema component: User
  Type: object
Document with components:
openapi: 3.1.1
info:
  title: API with Components
  version: 1.0.0
paths:
  /users/{userId}:
    get:
      operationId: getUser
      responses:
        "200":
          description: User details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
    parameters:
      - $ref: '#/components/parameters/UserIdParam'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
      required:
        - id
        - name
  parameters:
    UserIdParam:
      name: userId
      in: path
      required: true
      schema:
        type: integer
Example (WorkingWithJSONSchema)

Example_workingWithJSONSchema demonstrates how to work with JSON Schema directly. Shows how to unmarshal a JSONSchema from YAML or JSON and validate it manually.

package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/speakeasy-api/openapi/jsonschema/oas3"
	"github.com/speakeasy-api/openapi/marshaller"
)

func main() {
	ctx := context.Background()

	// Example JSON Schema as YAML
	schemaYAML := `
type: object
properties:
  id:
    type: integer
    format: int64
  name:
    type: string
    maxLength: 100
  email:
    type: string
    format: email
required:
  - id
  - name
  - email
`

	// Unmarshal directly to a JSONSchema using marshaller.Unmarshal
	var schema oas3.JSONSchema[oas3.Concrete]
	validationErrs, err := marshaller.Unmarshal(ctx, bytes.NewReader([]byte(schemaYAML)), &schema)
	if err != nil {
		panic(err)
	}

	// Validate manually
	additionalErrs := schema.Validate(ctx)
	validationErrs = append(validationErrs, additionalErrs...)

	if len(validationErrs) > 0 {
		for _, err := range validationErrs {
			fmt.Println("Validation error:", err.Error())
		}
	}

	// Access schema properties
	if schema.IsLeft() {
		schemaObj := schema.GetLeft()
		fmt.Println("Schema Types:")
		for _, t := range schemaObj.GetType() {
			fmt.Printf("  %s\n", t)
		}
		fmt.Printf("Required Fields: %v\n", schemaObj.GetRequired())
		fmt.Printf("Number of Properties: %d\n", schemaObj.GetProperties().Len())
	}
}
Output:

Schema Types:
  object
Required Fields: [id name email]
Number of Properties: 3

Index

Examples

Constants

View Source
const (
	Version      = "3.1.1"
	VersionMajor = 3
	VersionMinor = 1
	VersionPatch = 1

	Version30XMaxPatch = 4
	Version31XMaxPatch = 1
)

Version is the version of the OpenAPI Specification that this package conforms to.

Variables

This section is empty.

Functions

func Bundle added in v1.1.0

func Bundle(ctx context.Context, doc *OpenAPI, opts BundleOptions) error

Bundle transforms an OpenAPI document by bringing all external references into the components section, creating a self-contained document that maintains the reference structure but doesn't depend on external files. This operation modifies the document in place.

Why use Bundle?

  • **Create portable documents**: Combine multiple OpenAPI files into a single document while preserving references
  • **Maintain reference structure**: Keep the benefits of references for tooling that supports them
  • **Simplify distribution**: Share a single file that contains all dependencies
  • **Optimize for reference-aware tools**: Provide complete documents to tools that work well with references
  • **Prepare for further processing**: Create a foundation for subsequent inlining or other transformations
  • **Handle complex API architectures**: Combine modular API definitions into unified specifications

What you'll get:

Before bundling:

{
  "openapi": "3.1.0",
  "paths": {
    "/users": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "external_api.yaml#/User"
                }
              }
            }
          }
        }
      }
    }
  }
}

After bundling (with BundleNamingFilePath):

{
  "openapi": "3.1.0",
  "paths": {
    "/users": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/external_api_yaml~User"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "external_api_yaml~User": {
        "type": "object",
        "properties": {
          "id": {"type": "string"},
          "name": {"type": "string"}
        }
      }
    }
  }
}

Parameters:

  • ctx: Context for cancellation and timeout control
  • doc: The OpenAPI document to bundle (modified in place)
  • opts: Configuration options for bundling

Returns:

  • error: Any error that occurred during bundling

func Clean added in v1.6.0

func Clean(ctx context.Context, doc *OpenAPI) error

Clean removes unused components from the OpenAPI document. It walks through the document to track all referenced components and removes any components that are not referenced. Security schemes are handled specially as they can be referenced by name in security blocks rather than by $ref.

This function modifies the document in place.

Why use Clean?

  • **Reduce document size**: Remove unused component definitions that bloat the specification
  • **Improve clarity**: Keep only the components that are actually used in the API
  • **Optimize tooling performance**: Smaller documents with fewer unused components process faster
  • **Maintain clean specifications**: Prevent accumulation of dead code in API definitions
  • **Prepare for distribution**: Clean up specifications before sharing or publishing

What gets cleaned:

  • Unused schemas in components/schemas
  • Unused responses in components/responses
  • Unused parameters in components/parameters
  • Unused examples in components/examples
  • Unused request bodies in components/requestBodies
  • Unused headers in components/headers
  • Unused security schemes in components/securitySchemes (with special handling)
  • Unused links in components/links
  • Unused callbacks in components/callbacks
  • Unused path items in components/pathItems

Special handling for security schemes:

Security schemes can be referenced in two ways:

  1. By $ref (like other components)
  2. By name in security requirement objects (global or operation-level)

The Clean function handles both cases correctly.

Example usage:

// Load an OpenAPI document with potentially unused components
doc := &OpenAPI{...}

// Clean up unused components (modifies doc in place)
err := Clean(ctx, doc)
if err != nil {
	return fmt.Errorf("failed to clean document: %w", err)
}

// doc now has only the components that are actually referenced

Parameters:

  • ctx: Context for the operation
  • doc: The OpenAPI document to clean (modified in place)

Returns:

  • error: Any error that occurred during cleaning

func ExtractMethodAndPath added in v1.7.1

func ExtractMethodAndPath(locations Locations) (string, string)

ExtractMethodAndPath extracts the HTTP method and path from location context when walking operations. This utility function is designed to be used alongside Walk operations to determine the HTTP method and path that an operation relates to.

The function traverses the location context in reverse order to find: - The path from a "Paths" parent (e.g., "/users/{id}") - The HTTP method from a "PathItem" parent (e.g., "get", "post", "put", etc.)

Returns empty strings if the locations don't represent a valid operation context or if the location hierarchy doesn't match the expected OpenAPI structure.

Example usage:

for item := range openapi.Walk(ctx, doc) {
	err := item.Match(openapi.Matcher{
		Operation: func(op *openapi.Operation) error {
			method, path := openapi.ExtractMethodAndPath(item.Location)
			fmt.Printf("Found operation: %s %s\n", method, path)
			return nil
		},
	})
}

func GetParentType added in v1.7.1

func GetParentType(location LocationContext) string

GetParentType determines the type of the parent object in a location context. This utility function is used to identify the parent type when traversing OpenAPI document structures during walking operations.

Returns one of the following strings based on the parent type: - "Paths" for *openapi.Paths - "PathItem" for *openapi.ReferencedPathItem - "OpenAPI" for *openapi.OpenAPI - "Unknown" for any other type

This function is primarily used internally by ExtractMethodAndPath but is exposed as a public utility for advanced use cases where users need to inspect the parent type hierarchy during document traversal.

func Inline added in v1.1.0

func Inline(ctx context.Context, doc *OpenAPI, opts InlineOptions) error

Inline transforms an OpenAPI document by replacing all $ref references with their actual content, creating a self-contained document that doesn't depend on external definitions or component references. This operation modifies the document in place.

Why use Inline?

  • **Simplify document distribution**: Create standalone OpenAPI documents that can be shared without worrying about missing referenced files or component definitions
  • **AI and tooling integration**: Provide complete, self-contained OpenAPI documents to AI systems and tools that work better with fully expanded specifications
  • **Improve compatibility**: Some tools work better with fully expanded documents rather than ones with references
  • **Generate documentation**: Create complete API representations for documentation where all schemas and components are visible inline
  • **Optimize for specific use cases**: Eliminate the need for reference resolution in performance-critical applications
  • **Debug API issues**: See the full expanded document to understand how references resolve

What you'll get:

Before inlining:

{
  "openapi": "3.1.0",
  "paths": {
    "/users": {
      "get": {
        "responses": {
          "200": {"$ref": "#/components/responses/UserResponse"}
        }
      }
    }
  },
  "components": {
    "responses": {
      "UserResponse": {
        "description": "User response",
        "content": {
          "application/json": {
            "schema": {"$ref": "#/components/schemas/User"}
          }
        }
      }
    },
    "schemas": {
      "User": {"type": "object", "properties": {"name": {"type": "string"}}}
    }
  }
}

After inlining:

{
  "openapi": "3.1.0",
  "paths": {
    "/users": {
      "get": {
        "responses": {
          "200": {
            "description": "User response",
            "content": {
              "application/json": {
                "schema": {"type": "object", "properties": {"name": {"type": "string"}}}
              }
            }
          }
        }
      }
    }
  }
}

Handling References:

Unlike JSON Schema references, OpenAPI component references are simpler to handle since they don't typically have circular reference issues. The function will:

1. Walk through the entire OpenAPI document 2. For each reference encountered, resolve and inline it in place 3. For JSON schemas, use the existing oas3.Inline functionality 4. Optionally remove unused components after inlining

Example usage:

// Load an OpenAPI document with references
doc := &OpenAPI{...}

// Configure inlining
opts := InlineOptions{
	ResolveOptions: ResolveOptions{
		RootDocument: doc,
		TargetLocation: "openapi.yaml",
	},
	RemoveUnusedComponents: true, // Clean up unused components
}

// Inline all references (modifies doc in place)
err := Inline(ctx, doc, opts)
if err != nil {
	return fmt.Errorf("failed to inline document: %w", err)
}

// doc is now a self-contained OpenAPI document with all references expanded

Parameters:

  • ctx: Context for the operation
  • doc: The OpenAPI document to inline (modified in place)
  • opts: Configuration options for inlining

Returns:

  • error: Any error that occurred during inlining

func Join added in v1.2.0

func Join(ctx context.Context, mainDoc *OpenAPI, documents []JoinDocumentInfo, opts JoinOptions) error

Join combines multiple OpenAPI documents into one, using conflict resolution strategies similar to bundling but without inlining external references. This creates a single document that retains references to external documents while resolving conflicts between local components and operations.

The main document serves as the base:

  • Its Info and OpenAPI version fields are retained
  • For conflicting servers, security, and tags, the main document's values are kept

For other fields:

  • Operations, components, webhooks, and extensions are appended from all documents
  • Operation conflicts create new paths with fragments containing the file name
  • Component conflicts use the same strategy as bundling (counter or filepath naming)

Parameters:

  • ctx: Context for cancellation and timeout control
  • mainDoc: The main document that serves as the base (will be modified in place)
  • documents: Slice of JoinDocumentInfo containing additional documents and their file paths
  • opts: Configuration options for joining

Returns:

  • error: Any error that occurred during joining

func Localize added in v1.7.1

func Localize(ctx context.Context, doc *OpenAPI, opts LocalizeOptions) error

Localize transforms an OpenAPI document by copying all external reference files to a target directory and rewriting the references in the document to point to the localized files. This operation modifies the document in place.

Why use Localize?

  • **Create portable document bundles**: Copy all external dependencies into a single directory
  • **Simplify deployment**: Package all API definition files together for easy distribution
  • **Offline development**: Work with API definitions without external file dependencies
  • **Version control**: Keep all related files in the same repository structure
  • **CI/CD pipelines**: Ensure all dependencies are available in build environments
  • **Documentation generation**: Bundle all files needed for complete API documentation

What you'll get:

Before localization:

main.yaml:
  paths:
    /users:
      get:
        responses:
          '200':
            content:
              application/json:
                schema:
                  $ref: "./components.yaml#/components/schemas/User"

components.yaml:
  components:
    schemas:
      User:
        properties:
          address:
            $ref: "./schemas/address.yaml#/Address"

After localization (files copied to target directory):

target/main.yaml:
  paths:
    /users:
      get:
        responses:
          '200':
            content:
              application/json:
                schema:
                  $ref: "components.yaml#/components/schemas/User"

target/components.yaml:
  components:
    schemas:
      User:
        properties:
          address:
            $ref: "schemas-address.yaml#/Address"

target/schemas-address.yaml:
  Address:
    type: object
    properties:
      street: {type: string}

Parameters:

  • ctx: Context for cancellation and timeout control
  • doc: The OpenAPI document to localize (modified in place)
  • opts: Configuration options for localization

Returns:

  • error: Any error that occurred during localization

func Marshal

func Marshal(ctx context.Context, openapi *OpenAPI, w io.Writer) error

Marshal will marshal the provided OpenAPI document to the provided io.Writer.

func Optimize added in v1.6.0

func Optimize(ctx context.Context, doc *OpenAPI, nameCallback OptimizeNameCallback) error

Optimize finds all inline JSON schemas with the same content (hash) and replaces them with references to existing or newly created components.

The optimization process:

  1. Walks through all JSON schemas and collects hashes of inline schemas (except top-level components)
  2. Only considers complex schemas (object schemas, enums, oneOf/allOf/anyOf, etc.) - not simple types
  3. For schemas with multiple matches, tries to match them to existing components first
  4. Creates new components with Schema_{hash} names for unmatched duplicates
  5. Replaces inline schemas with references to the components

The nameCallback allows customization of component names. If nil, default names are used.

This function modifies the document in place.

Why use Optimize?

  • **Reduce document size**: Eliminate duplicate inline schema definitions
  • **Improve maintainability**: Centralize schema definitions in components
  • **Enhance reusability**: Make schemas available for reference throughout the document
  • **Optimize tooling performance**: Reduce parsing overhead from duplicate schemas
  • **Standardize structure**: Follow OpenAPI best practices for schema organization

Example usage:

// Load an OpenAPI document with duplicate inline schemas
doc := &OpenAPI{...}

// Optimize with default naming
err := Optimize(ctx, doc, nil)
if err != nil {
	return fmt.Errorf("failed to optimize document: %w", err)
}

// Optimize with custom naming
err = Optimize(ctx, doc, func(suggested, hash string, locations []string, schema *oas3.JSONSchema[oas3.Referenceable]) string {
	return "CustomSchema_" + hash[:8]
})

Parameters:

  • ctx: Context for the operation
  • doc: The OpenAPI document to optimize (modified in place)
  • nameCallback: Optional callback to customize component names

Returns:

  • error: Any error that occurred during optimization

func Sync

Sync will sync the high-level model to the core model. This is useful when creating or mutating a high-level model and wanting access to the yaml nodes that back it.

func Upgrade

func Upgrade(ctx context.Context, doc *OpenAPI, opts ...Option[UpgradeOptions]) (bool, error)

Upgrade upgrades any OpenAPI 3x document to OpenAPI 3.1.1 (the latest version currently supported). It currently won't resolve any external references, so only this document itself will be upgraded.

func Walk

func Walk[T any](ctx context.Context, start *T) iter.Seq[WalkItem]

Walk returns an iterator that yields MatchFunc items for each model in the provided OpenAPI model. Users can iterate over the results using a for loop and break out at any time. When called with *OpenAPI, it walks the entire document. When called with other types, it walks from that specific component.

Types

type BundleNamingStrategy added in v1.1.0

type BundleNamingStrategy int

BundleNamingStrategy defines how external references should be named when bundled.

const (
	// BundleNamingCounter uses counter-based suffixes like User_1, User_2 for conflicts
	BundleNamingCounter BundleNamingStrategy = iota
	// BundleNamingFilePath uses file path-based naming like file_path_somefile_yaml~User
	BundleNamingFilePath
)

type BundleOptions added in v1.1.0

type BundleOptions struct {
	// ResolveOptions are the options to use when resolving references during bundling.
	ResolveOptions ResolveOptions
	// NamingStrategy determines how external references are named when brought into components.
	NamingStrategy BundleNamingStrategy
}

BundleOptions represents the options available when bundling an OpenAPI document.

type Callback

type Callback struct {
	marshaller.Model[core.Callback]
	sequencedmap.Map[expression.Expression, *ReferencedPathItem]

	// Extensions provides a list of extensions to the Callback object.
	Extensions *extensions.Extensions
}

Callback represents a set of callbacks related to the parent operation. The keys that represent the path items are a runtime expression that can be evaluated in the context of a request/response from the parent operation. Callback embeds sequencedmap.Map[string, *ReferencedPathItem] so all map operations are supported.

func NewCallback

func NewCallback() *Callback

NewCallback creates a new Callback object with the embedded map initialized.

func (*Callback) GetExtensions

func (c *Callback) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Callback) Validate

func (c *Callback) Validate(ctx context.Context, opts ...validation.Option) []error

type Components

type Components struct {
	marshaller.Model[core.Components]

	// Schemas is a map of reusable Schema Objects.
	Schemas *sequencedmap.Map[string, *oas3.JSONSchema[oas3.Referenceable]]
	// Responses is a map of reusable Response Objects.
	Responses *sequencedmap.Map[string, *ReferencedResponse]
	// Parameters is a map of reusable Parameter Objects.
	Parameters *sequencedmap.Map[string, *ReferencedParameter]
	// Examples is a map of reusable Example Objects.
	Examples *sequencedmap.Map[string, *ReferencedExample]
	// RequestBodies is a map of reusable Request Body Objects.
	RequestBodies *sequencedmap.Map[string, *ReferencedRequestBody]
	// Headers is a map of reusable Header Objects.
	Headers *sequencedmap.Map[string, *ReferencedHeader]
	// SecuritySchemes is a map of reusable Security Scheme Objects.
	SecuritySchemes *sequencedmap.Map[string, *ReferencedSecurityScheme]
	// Links is a map of reusable Link Objects.
	Links *sequencedmap.Map[string, *ReferencedLink]
	// Callbacks is a map of reusable Callback Objects.
	Callbacks *sequencedmap.Map[string, *ReferencedCallback]
	// PathItems is a map of reusable Path Item Objects.
	PathItems *sequencedmap.Map[string, *ReferencedPathItem]

	// Extensions provides a list of extensions to the Components object.
	Extensions *extensions.Extensions
}

Components is a container for the reusable objects available to the API.

func (*Components) GetCallbacks

func (c *Components) GetCallbacks() *sequencedmap.Map[string, *ReferencedCallback]

GetCallbacks returns the value of the Callbacks field. Returns nil if not set.

func (*Components) GetExamples

func (c *Components) GetExamples() *sequencedmap.Map[string, *ReferencedExample]

GetExamples returns the value of the Examples field. Returns nil if not set.

func (*Components) GetExtensions

func (c *Components) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Components) GetHeaders

func (c *Components) GetHeaders() *sequencedmap.Map[string, *ReferencedHeader]

GetHeaders returns the value of the Headers field. Returns nil if not set.

func (c *Components) GetLinks() *sequencedmap.Map[string, *ReferencedLink]

GetLink returns the value of the Links field. Returns nil if not set.

func (*Components) GetParameters

func (c *Components) GetParameters() *sequencedmap.Map[string, *ReferencedParameter]

GetParameters returns the value of the Parameters field. Returns nil if not set.

func (*Components) GetPathItems

func (c *Components) GetPathItems() *sequencedmap.Map[string, *ReferencedPathItem]

GetPathItems returns the value of the PathItems field. Returns nil if not set.

func (*Components) GetRequestBodies

func (c *Components) GetRequestBodies() *sequencedmap.Map[string, *ReferencedRequestBody]

GetRequestBodies returns the value of the RequestBodies field. Returns nil if not set.

func (*Components) GetResponses

func (c *Components) GetResponses() *sequencedmap.Map[string, *ReferencedResponse]

GetResponses returns the value of the Responses field. Returns nil if not set.

func (*Components) GetSchemas

GetSchemas returns the value of the Schemas field. Returns nil if not set.

func (*Components) GetSecuritySchemes

func (c *Components) GetSecuritySchemes() *sequencedmap.Map[string, *ReferencedSecurityScheme]

GetSecuritySchemes returns the value of the SecuritySchemes field. Returns nil if not set.

func (*Components) Validate

func (c *Components) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Components object against the OpenAPI Specification.

type ConflictingOperation added in v1.7.1

type ConflictingOperation struct {
	Method    HTTPMethod
	Operation *Operation
}

ConflictingOperation represents an operation that conflicts with an existing one

type Contact

type Contact struct {
	marshaller.Model[core.Contact]

	// Name is the identifying name of the contact person/organization for the API.
	Name *string
	// URL is the URL for the contact person/organization. It MUST be in the format of a URI.
	URL *string
	// Email is the email address for the contact person/organization. It MUST be in the format of an email address.
	Email *string
	// Extensions provides a list of extensions to the Contact object.
	Extensions *extensions.Extensions
}

Contact information for the documented API.

func (*Contact) GetEmail

func (c *Contact) GetEmail() string

GetEmail returns the value of the Email field. Returns empty string if not set.

func (*Contact) GetExtensions

func (c *Contact) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Contact) GetName

func (c *Contact) GetName() string

GetName returns the value of the Name field. Returns empty string if not set.

func (*Contact) GetURL

func (c *Contact) GetURL() string

GetURL returns the value of the URL field. Returns empty string if not set.

func (*Contact) Validate

func (c *Contact) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Contact object against the OpenAPI Specification.

type Encoding

type Encoding struct {
	marshaller.Model[core.Encoding]

	// ContentType is a string that describes the media type of the encoding. Can be a specific media type (e.g. application/json), a wildcard media type (e.g. image/*) or a comma-separated list of the two types.
	ContentType *string
	// Headers represents additional headers that can be added to the request.
	Headers *sequencedmap.Map[string, *ReferencedHeader]
	// Style describes how the property is serialized based on its type.
	Style *SerializationStyle
	// Explode determines for array or object properties whether separate parameters should be generated for each item in the array or object.
	Explode *bool
	// AllowReserved determines if the value of this parameter can contain reserved characters as defined by RFC3986.
	AllowReserved *bool

	// Extensions provides a list of extensions to the Encoding object.
	Extensions *extensions.Extensions
}

Encoding represents a single encoding definition applied to a single schema property.

func (*Encoding) GetAllowReserved

func (e *Encoding) GetAllowReserved() bool

GetAllowReserved will return the value of the allowReserved or the default false.

func (*Encoding) GetContentType

func (e *Encoding) GetContentType(schema *oas3.JSONSchema[oas3.Concrete]) string

GetContentType will return the value of the content type or the default based on the schema of the associated property. schema can either be the schema of the property or nil, if nil the provided content type will be used or the default "application/octet-stream" will be used.

func (*Encoding) GetContentTypeValue

func (e *Encoding) GetContentTypeValue() string

GetContentTypeValue returns the raw value of the ContentType field. Returns empty string if not set.

func (*Encoding) GetExplode

func (e *Encoding) GetExplode() bool

GetExplode will return the value of the explode or the default based on the style.

func (*Encoding) GetExtensions

func (e *Encoding) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Encoding) GetHeaders

func (e *Encoding) GetHeaders() *sequencedmap.Map[string, *ReferencedHeader]

GetHeaders returns the value of the Headers field. Returns nil if not set.

func (*Encoding) GetStyle

func (e *Encoding) GetStyle() SerializationStyle

GetStyle will return the value of the style or the default SerializationStyleForm.

func (*Encoding) Validate

func (e *Encoding) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Encoding object against the OpenAPI Specification.

type Example

type Example struct {
	marshaller.Model[core.Example]

	// Summary is a short summary of the example.
	Summary *string
	// Description is a description of the example.
	Description *string
	// Value is the example value. Mutually exclusive with ExternalValue.
	Value values.Value
	// ExternalValue is a URI to the location of the example value. May be relative to the location of the document. Mutually exclusive with Value.
	ExternalValue *string
	// Extensions provides a list of extensions to the Example object.
	Extensions *extensions.Extensions
}

func (*Example) GetDescription

func (e *Example) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Example) GetExtensions

func (e *Example) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Example) GetExternalValue

func (e *Example) GetExternalValue() string

GetExternalValue returns the value of the ExternalValue field. Returns empty string if not set.

func (*Example) GetSummary

func (e *Example) GetSummary() string

GetSummary returns the value of the Summary field. Returns empty string if not set.

func (*Example) GetValue

func (e *Example) GetValue() values.Value

GetValue returns the value of the Value field. Returns nil if not set.

func (*Example) ResolveExternalValue

func (e *Example) ResolveExternalValue(ctx context.Context) (values.Value, error)

ResolveExternalValue will resolve the external value returning the value referenced.

func (*Example) Validate

func (e *Example) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Example object against the OpenAPI Specification.

type HTTPMethod

type HTTPMethod string

HTTPMethod is an enum representing the HTTP methods available in the OpenAPI specification.

const (
	// HTTPMethodGet represents the HTTP GET method.
	HTTPMethodGet HTTPMethod = "get"
	// HTTPMethodPut represents the HTTP PUT method.
	HTTPMethodPut HTTPMethod = "put"
	// HTTPMethodPost represents the HTTP POST method.
	HTTPMethodPost HTTPMethod = "post"
	// HTTPMethodDelete represents the HTTP DELETE method.
	HTTPMethodDelete HTTPMethod = "delete"
	// HTTPMethodOptions represents the HTTP OPTIONS method.
	HTTPMethodOptions HTTPMethod = "options"
	// HTTPMethodHead represents the HTTP HEAD method.
	HTTPMethodHead HTTPMethod = "head"
	// HTTPMethodPatch represents the HTTP PATCH method.
	HTTPMethodPatch HTTPMethod = "patch"
	// HTTPMethodTrace represents the HTTP TRACE method.
	HTTPMethodTrace HTTPMethod = "trace"
)

func (HTTPMethod) Is

func (m HTTPMethod) Is(method string) bool
type Header struct {
	marshaller.Model[core.Header]

	// Description is a brief description of the header. May contain CommonMark syntax.
	Description *string
	// Required determines whether this header is mandatory.
	Required *bool
	// Deprecated describes whether this header is deprecated.
	Deprecated *bool
	// Style determines the serialization style of the header.
	Style *SerializationStyle
	// Explode determines for array and object values whether separate headers should be generated for each item in the array or object.
	Explode *bool
	// Schema is the schema defining the type used for the header. Mutually exclusive with Content.
	Schema *oas3.JSONSchema[oas3.Referenceable]
	// Content represents the content type and schema of a header. Mutually exclusive with Schema.
	Content *sequencedmap.Map[string, *MediaType]
	// Example is an example of the header's value. Mutually exclusive with Examples.
	Example values.Value
	// Examples is a map of examples of the header's value. Mutually exclusive with Example.
	Examples *sequencedmap.Map[string, *ReferencedExample]
	// Extensions provides a list of extensions to the Header object.
	Extensions *extensions.Extensions
}

Header represents a single header parameter.

func (*Header) GetContent

func (h *Header) GetContent() *sequencedmap.Map[string, *MediaType]

GetContent returns the value of the Content field. Returns nil if not set.

func (*Header) GetDeprecated

func (h *Header) GetDeprecated() bool

GetDeprecated returns the value of the Deprecated field. False by default if not set.

func (*Header) GetDescription

func (h *Header) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Header) GetExample

func (h *Header) GetExample() values.Value

GetExample returns the value of the Example field. Returns nil if not set.

func (*Header) GetExamples

func (h *Header) GetExamples() *sequencedmap.Map[string, *ReferencedExample]

GetExamples returns the value of the Examples field. Returns nil if not set.

func (*Header) GetExplode

func (h *Header) GetExplode() bool

GetExplode returns the value of the Explode field. False by default if not set.

func (*Header) GetExtensions

func (h *Header) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Header) GetRequired

func (h *Header) GetRequired() bool

GetRequired returns the value of the Required field. False by default if not set.

func (*Header) GetSchema

func (h *Header) GetSchema() *oas3.JSONSchema[oas3.Referenceable]

GetSchema returns the value of the Schema field. Returns nil if not set.

func (*Header) GetStyle

func (h *Header) GetStyle() SerializationStyle

GetStyle returns the value of the Style field. SerializationStyleSimple by default if not set.

func (*Header) Validate

func (h *Header) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Header object against the OpenAPI Specification.

type Info

type Info struct {
	marshaller.Model[core.Info]

	// The title of the API.
	Title string
	// The version of this OpenAPI document, distinct from the API version.
	Version string
	// A short summary describing the API.
	Summary *string
	// A description of the API. May contain CommonMark syntax.
	Description *string
	// A URI to the Terms of Service for the API. It MUST be in the format of a URI.
	TermsOfService *string
	// Contact information for the documented API.
	Contact *Contact
	// The license information for the API.
	License *License
	// Extensions provides a list of extensions to the Info object.
	Extensions *extensions.Extensions
}

Info provides various information about the API and document.

func (*Info) GetContact

func (i *Info) GetContact() *Contact

GetContact returns the value of the Contact field. Returns nil if not set.

func (*Info) GetDescription

func (i *Info) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Info) GetExtensions

func (i *Info) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Info) GetLicense

func (i *Info) GetLicense() *License

GetLicense returns the value of the License field. Returns nil if not set.

func (*Info) GetSummary

func (i *Info) GetSummary() string

GetSummary returns the value of the Summary field. Returns empty string if not set.

func (*Info) GetTermsOfService

func (i *Info) GetTermsOfService() string

GetTermsOfService returns the value of the TermsOfService field. Returns empty string if not set.

func (*Info) GetTitle

func (i *Info) GetTitle() string

GetTitle returns the value of the Title field. Returns empty string if not set.

func (*Info) GetVersion

func (i *Info) GetVersion() string

GetVersion returns the value of the Version field. Returns empty string if not set.

func (*Info) Validate

func (i *Info) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Info object against the OpenAPI Specification.

type InlineOptions added in v1.1.0

type InlineOptions struct {
	// ResolveOptions are the options to use when resolving references during inlining.
	ResolveOptions ResolveOptions
	// RemoveUnusedComponents determines whether to remove components that are no longer referenced after inlining.
	RemoveUnusedComponents bool
}

InlineOptions represents the options available when inlining an OpenAPI document.

type JoinConflictStrategy added in v1.2.0

type JoinConflictStrategy int

JoinConflictStrategy defines how conflicts should be resolved when joining documents.

const (
	// JoinConflictCounter uses counter-based suffixes like User_1, User_2 for conflicts
	JoinConflictCounter JoinConflictStrategy = iota
	// JoinConflictFilePath uses file path-based naming like file_path_somefile_yaml~User
	JoinConflictFilePath
)

type JoinDocumentInfo added in v1.2.0

type JoinDocumentInfo struct {
	Document *OpenAPI
	FilePath string
}

JoinDocumentInfo holds information about a document being joined.

type JoinOptions added in v1.2.0

type JoinOptions struct {
	// ConflictStrategy determines how conflicts are resolved when joining documents.
	ConflictStrategy JoinConflictStrategy
	// DocumentPaths maps each document to its file path for conflict resolution.
	// The key should match the document's position in the documents slice.
	DocumentPaths map[int]string
}

JoinOptions represents the options available when joining OpenAPI documents.

type License

type License struct {
	marshaller.Model[core.License]

	// Name is the name of the license used for the API.
	Name string
	// A SPDX license identifier for the license used for the API. This field is mutually exclusive of the URL field.
	Identifier *string
	// URL is the URL to the license used for the API. It MUST be in the format of a URI. This field is mutually exclusive of the Identifier field.
	URL *string
	// Extensions provides a list of extensions to the License object.
	Extensions *extensions.Extensions
}

License information for the documented API.

func (*License) GetExtensions

func (l *License) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*License) GetIdentifier

func (l *License) GetIdentifier() string

GetIdentifier returns the value of the Identifier field. Returns empty string if not set.

func (*License) GetName

func (l *License) GetName() string

GetName returns the value of the Name field. Returns empty string if not set.

func (*License) GetURL

func (l *License) GetURL() string

GetURL returns the value of the URL field. Returns empty string if not set.

func (*License) Validate

func (l *License) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the License object against the OpenAPI Specification.

type Link struct {
	marshaller.Model[core.Link]

	// OperationID is a identified to an existing operation in the API. Mutually exclusive with OperationRef.
	OperationID *string
	// OperationRef is a reference to an existing operation in the API. Mutually exclusive with OperationID.
	OperationRef *string
	// Parameters is a map of parameter names to values or runtime expressions to populate the referenced operation.
	Parameters *sequencedmap.Map[string, expression.ValueOrExpression]
	// RequestBody is either a value or a runtime expression to populate the referenced operation.
	RequestBody expression.ValueOrExpression
	// Description is a description of the link. May contain CommonMark syntax.
	Description *string
	// Server is a server object to be used by the target operation.
	Server *Server

	// Extensions provides a list of extensions to the Link object.
	Extensions *extensions.Extensions
}

func (*Link) GetDescription

func (l *Link) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Link) GetExtensions

func (l *Link) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Link) GetOperationID

func (l *Link) GetOperationID() string

GetOperationID returns the value of the OperationID field. Returns empty string if not set.

func (*Link) GetOperationRef

func (l *Link) GetOperationRef() string

GetOperationRef returns the value of the OperationRef field. Returns empty string if not set.

func (*Link) GetParameters

func (l *Link) GetParameters() *sequencedmap.Map[string, expression.ValueOrExpression]

GetParameters returns the value of the Parameters field. Returns nil if not set.

func (*Link) GetRequestBody

func (l *Link) GetRequestBody() expression.ValueOrExpression

GetRequestBody returns the value of the RequestBody field. Returns nil if not set.

func (*Link) GetServer

func (l *Link) GetServer() *Server

GetServer returns the value of the Server field. Returns nil if not set.

func (*Link) ResolveOperation

func (l *Link) ResolveOperation(ctx context.Context) (*Operation, error)

func (*Link) Validate

func (l *Link) Validate(ctx context.Context, opts ...validation.Option) []error

type LocalizeNamingStrategy added in v1.7.1

type LocalizeNamingStrategy int

LocalizeNamingStrategy defines how external reference files should be named when localized.

const (
	// LocalizeNamingPathBased uses path-based naming like "schemas-address.yaml" for conflicts
	LocalizeNamingPathBased LocalizeNamingStrategy = iota
	// LocalizeNamingCounter uses counter-based suffixes like "address_1.yaml" for conflicts
	LocalizeNamingCounter
)

type LocalizeOptions added in v1.7.1

type LocalizeOptions struct {
	// DocumentLocation is the location of the document being localized.
	DocumentLocation string
	// TargetDirectory is the directory where localized files will be written.
	TargetDirectory string
	// VirtualFS is the file system interface used for reading and writing files.
	VirtualFS system.WritableVirtualFS
	// HTTPClient is the HTTP client to use for fetching remote references.
	HTTPClient system.Client
	// NamingStrategy determines how external reference files are named when localized.
	NamingStrategy LocalizeNamingStrategy
}

LocalizeOptions represents the options available when localizing an OpenAPI document.

type LocationContext

type LocationContext = walkpkg.LocationContext[MatchFunc]

Use the shared walking infrastructure

type Locations

type Locations = walkpkg.Locations[MatchFunc]

type MatchFunc

type MatchFunc func(Matcher) error

MatchFunc represents a particular model in the OpenAPI document that can be matched. Pass it a Matcher with the appropriate functions populated to match the model type(s) you are interested in.

type Matcher

type Matcher struct {
	OpenAPI                  func(*OpenAPI) error
	Info                     func(*Info) error
	Contact                  func(*Contact) error
	License                  func(*License) error
	ExternalDocs             func(*oas3.ExternalDocumentation) error
	Tag                      func(*Tag) error
	Server                   func(*Server) error
	ServerVariable           func(*ServerVariable) error
	Security                 func(*SecurityRequirement) error
	Paths                    func(*Paths) error
	ReferencedPathItem       func(*ReferencedPathItem) error
	ReferencedParameter      func(*ReferencedParameter) error
	Schema                   func(*oas3.JSONSchema[oas3.Referenceable]) error
	Discriminator            func(*oas3.Discriminator) error
	XML                      func(*oas3.XML) error
	MediaType                func(*MediaType) error
	Encoding                 func(*Encoding) error
	ReferencedHeader         func(*ReferencedHeader) error
	ReferencedExample        func(*ReferencedExample) error
	Operation                func(*Operation) error
	ReferencedRequestBody    func(*ReferencedRequestBody) error
	Responses                func(*Responses) error
	ReferencedResponse       func(*ReferencedResponse) error
	ReferencedLink           func(*ReferencedLink) error
	ReferencedCallback       func(*ReferencedCallback) error
	Components               func(*Components) error
	ReferencedSecurityScheme func(*ReferencedSecurityScheme) error
	OAuthFlows               func(*OAuthFlows) error
	OAuthFlow                func(*OAuthFlow) error
	Extensions               func(*extensions.Extensions) error
	Any                      func(any) error // Any will be called along with the other functions above on a match of a model
}

Matcher is a struct that can be used to match specific nodes in the OpenAPI document.

type MediaType

type MediaType struct {
	marshaller.Model[core.MediaType]

	// Schema is the schema defining the type used for the parameter.
	Schema *oas3.JSONSchema[oas3.Referenceable]
	// Encoding is a map allowing for more complex encoding scenarios.
	Encoding *sequencedmap.Map[string, *Encoding]
	// Example is an example of the media type's value.
	Example values.Value
	// Examples is a map of examples of the media type's value.
	Examples *sequencedmap.Map[string, *ReferencedExample]

	// Extensions provides a list of extensions to the MediaType object.
	Extensions *extensions.Extensions
}

MediaType provides a schema and examples for the associated media type.

func (*MediaType) GetEncoding

func (m *MediaType) GetEncoding() *sequencedmap.Map[string, *Encoding]

GetEncoding returns the value of the Encoding field. Returns nil if not set.

func (*MediaType) GetExample

func (m *MediaType) GetExample() values.Value

GetExample returns the value of the Example field. Returns nil if not set.

func (*MediaType) GetExamples

func (m *MediaType) GetExamples() *sequencedmap.Map[string, *ReferencedExample]

GetExamples returns the value of the Examples field. Returns nil if not set.

func (*MediaType) GetExtensions

func (m *MediaType) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*MediaType) GetSchema

func (m *MediaType) GetSchema() *oas3.JSONSchema[oas3.Referenceable]

GetSchema returns the value of the Schema field. Returns nil if not set.

func (*MediaType) Validate

func (m *MediaType) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the MediaType object against the OpenAPI Specification.

type OAuthFlow

type OAuthFlow struct {
	marshaller.Model[core.OAuthFlow]

	// AuthorizationUrl is a URL to be used for obtaining authorization.
	AuthorizationURL *string
	// TokenUrl is a URL to be used for obtaining access tokens.
	TokenURL *string
	// RefreshUrl is a URL to be used for refreshing access tokens.
	RefreshURL *string
	// Scopes is a map between the name of the scope and a short description of the scope.
	Scopes *sequencedmap.Map[string, string]
	// Extensions provides a list of extensions to the OAuthFlow object.
	Extensions *extensions.Extensions
}

OAuthFlow represents the configuration details for a supported OAuth flow.

func (*OAuthFlow) GetAuthorizationURL

func (o *OAuthFlow) GetAuthorizationURL() string

GetAuthorizationURL returns the value of the AuthorizationURL field. Returns empty string if not set.

func (*OAuthFlow) GetExtensions

func (o *OAuthFlow) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*OAuthFlow) GetRefreshURL

func (o *OAuthFlow) GetRefreshURL() string

GetRefreshURL returns the value of the RefreshURL field. Returns empty string if not set.

func (*OAuthFlow) GetScopes

func (o *OAuthFlow) GetScopes() *sequencedmap.Map[string, string]

GetScopes returns the value of the Scopes field. Returns nil if not set.

func (*OAuthFlow) GetTokenURL

func (o *OAuthFlow) GetTokenURL() string

GetTokenURL returns the value of the TokenURL field. Returns empty string if not set.

func (*OAuthFlow) Validate

func (o *OAuthFlow) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the OAuthFlow object against the OpenAPI Specification.

type OAuthFlowType

type OAuthFlowType string
const (
	OAuthFlowTypeImplicit          OAuthFlowType = "implicit"
	OAuthFlowTypePassword          OAuthFlowType = "password"
	OAuthFlowTypeClientCredentials OAuthFlowType = "clientCredentials"
	OAuthFlowTypeAuthorizationCode OAuthFlowType = "authorizationCode"
)

type OAuthFlows

type OAuthFlows struct {
	marshaller.Model[core.OAuthFlows]

	// Implicit represents configuration fields for the OAuth2 Implicit flow.
	Implicit *OAuthFlow
	// Password represents configuration fields for the OAuth2 Resource Owner Password flow.
	Password *OAuthFlow
	// ClientCredentials represents configuration fields for the OAuth2 Client Credentials flow.
	ClientCredentials *OAuthFlow
	// AuthorizationCode represents configuration fields for the OAuth2 Authorization Code flow.
	AuthorizationCode *OAuthFlow

	// Extensions provides a list of extensions to the OAuthFlows object.
	Extensions *extensions.Extensions
}

OAuthFlows represents the configuration of the supported OAuth flows.

func (*OAuthFlows) GetAuthorizationCode

func (o *OAuthFlows) GetAuthorizationCode() *OAuthFlow

GetAuthorizationCode returns the value of the AuthorizationCode field. Returns nil if not set.

func (*OAuthFlows) GetClientCredentials

func (o *OAuthFlows) GetClientCredentials() *OAuthFlow

GetClientCredentials returns the value of the ClientCredentials field. Returns nil if not set.

func (*OAuthFlows) GetExtensions

func (o *OAuthFlows) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*OAuthFlows) GetImplicit

func (o *OAuthFlows) GetImplicit() *OAuthFlow

GetImplicit returns the value of the Implicit field. Returns nil if not set.

func (*OAuthFlows) GetPassword

func (o *OAuthFlows) GetPassword() *OAuthFlow

GetPassword returns the value of the Password field. Returns nil if not set.

func (*OAuthFlows) Validate

func (o *OAuthFlows) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the OAuthFlows object against the OpenAPI Specification.

type OpenAPI

type OpenAPI struct {
	marshaller.Model[core.OpenAPI]

	// OpenAPI is the version of the OpenAPI Specification that this document conforms to.
	OpenAPI string
	// Info provides various information about the API and document.
	Info Info
	// ExternalDocs provides additional external documentation for this API.
	ExternalDocs *oas3.ExternalDocumentation
	// Tags is a list of tags used by the document.
	Tags []*Tag
	// Servers is an array of information about servers available to provide the functionality described in the API.
	Servers []*Server
	// Security is a declaration of which security mechanisms can be used for this API.
	Security []*SecurityRequirement
	// Paths is a map of relative endpoint paths to their corresponding PathItem objects.
	Paths *Paths
	// Webhooks are the incoming webhooks associated with this API.
	Webhooks *sequencedmap.Map[string, *ReferencedPathItem]

	// Components is a container for the reusable objects available to the API.
	Components *Components

	// JSONSchemaDialect is the default value for the $schema keyword within Schema objects in this document. It MUST be in the format of a URI.
	JSONSchemaDialect *string

	// Extensions provides a list of extensions to the OpenAPI document.
	Extensions *extensions.Extensions
}

OpenAPI represents an OpenAPI document compatible with the OpenAPI Specification 3.0.X and 3.1.X. Where the specification differs between versions the

func Bootstrap added in v1.3.0

func Bootstrap() *OpenAPI

Bootstrap creates a new OpenAPI document with best practice examples. This serves as a template demonstrating proper structure for operations, components, security schemes, servers, tags, and references.

func Unmarshal

func Unmarshal(ctx context.Context, doc io.Reader, opts ...Option[UnmarshalOptions]) (*OpenAPI, []error, error)

Unmarshal will unmarshal and validate an OpenAPI document from the provided io.Reader. Validation can be skipped by using openapi.WithSkipValidation() as one of the options when calling this function.

func (*OpenAPI) GetComponents

func (o *OpenAPI) GetComponents() *Components

GetComponents returns the value of the Components field. Returns nil if not set.

func (*OpenAPI) GetExtensions

func (o *OpenAPI) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*OpenAPI) GetExternalDocs

func (o *OpenAPI) GetExternalDocs() *oas3.ExternalDocumentation

GetExternalDocs returns the value of the ExternalDocs field. Returns nil if not set.

func (*OpenAPI) GetInfo

func (o *OpenAPI) GetInfo() *Info

GetInfo returns the value of the Info field. Returns nil if not set.

func (*OpenAPI) GetJSONSchemaDialect

func (o *OpenAPI) GetJSONSchemaDialect() string

GetJSONSchemaDialect returns the value of the JSONSchemaDialect field. Returns empty string if not set.

func (*OpenAPI) GetOpenAPI

func (o *OpenAPI) GetOpenAPI() string

GetOpenAPI returns the value of the OpenAPI field. Returns empty string if not set.

func (*OpenAPI) GetPaths

func (o *OpenAPI) GetPaths() *Paths

GetPaths returns the value of the Paths field. Returns nil if not set.

func (*OpenAPI) GetSecurity

func (o *OpenAPI) GetSecurity() []*SecurityRequirement

GetSecurity returns the value of the Security field. Returns nil if not set.

func (*OpenAPI) GetServers

func (o *OpenAPI) GetServers() []*Server

GetServers returns the value of the Servers field. Returns a default server of "/" if not set.

func (*OpenAPI) GetTags

func (o *OpenAPI) GetTags() []*Tag

GetTags returns the value of the Tags field. Returns nil if not set.

func (*OpenAPI) GetWebhooks

func (o *OpenAPI) GetWebhooks() *sequencedmap.Map[string, *ReferencedPathItem]

GetWebhooks returns the value of the Webhooks field. Returns nil if not set.

func (*OpenAPI) ResolveAllReferences

func (o *OpenAPI) ResolveAllReferences(ctx context.Context, opts ResolveAllOptions) ([]error, error)

ResolveAllReferences will resolve all references in the OpenAPI document, allowing them to be resolved and cached in a single operation.

func (*OpenAPI) Validate

func (o *OpenAPI) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the OpenAPI object against the OpenAPI Specification.

type Operation

type Operation struct {
	marshaller.Model[core.Operation]

	// OperationID is a unique string used to identify the operation.
	OperationID *string
	// Summary is a short summary of what the operation does.
	Summary *string
	// Description is a verbose explanation of the operation behavior. May contain CommonMark syntax.
	Description *string
	// Tags is a list of tags for API documentation control.
	Tags []string
	// Servers is an alternative server array to service this operation.
	Servers []*Server
	// Security is a declaration of which security mechanisms can be used for this operation.
	Security []*SecurityRequirement

	// Parameters is a list of parameters that are applicable for this operation.
	Parameters []*ReferencedParameter
	// RequestBody is the request body applicable for this operation.
	RequestBody *ReferencedRequestBody
	// Responses is the list of possible responses as they are returned from executing this operation.
	Responses *Responses
	// Callbacks is a map of possible out-of band callbacks related to the parent operation.
	Callbacks *sequencedmap.Map[string, *ReferencedCallback]

	// Deprecated declares this operation to be deprecated.
	Deprecated *bool
	// ExternalDocs is additional external documentation for this operation.
	ExternalDocs *oas3.ExternalDocumentation

	// Extensions provides a list of extensions to the Operation object.
	Extensions *extensions.Extensions
}

Operation represents a single API operation on a path.

func (*Operation) GetCallbacks

func (o *Operation) GetCallbacks() *sequencedmap.Map[string, *ReferencedCallback]

GetCallbacks returns the value of the Callbacks field. Returns nil if not set.

func (*Operation) GetDeprecated

func (o *Operation) GetDeprecated() bool

GetDeprecated returns the value of the Deprecated field. False by default if not set.

func (*Operation) GetDescription

func (o *Operation) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Operation) GetExtensions

func (o *Operation) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Operation) GetExternalDocs

func (o *Operation) GetExternalDocs() *oas3.ExternalDocumentation

GetExternalDocs returns the value of the ExternalDocs field. Returns nil if not set.

func (*Operation) GetOperationID

func (o *Operation) GetOperationID() string

GetOperationID returns the value of the OperationID field. Returns empty string if not set.

func (*Operation) GetParameters

func (o *Operation) GetParameters() []*ReferencedParameter

GetParameters returns the value of the Parameters field. Returns nil if not set.

func (*Operation) GetRequestBody

func (o *Operation) GetRequestBody() *ReferencedRequestBody

GetRequestBody returns the value of the RequestBody field. Returns nil if not set.

func (*Operation) GetResponses

func (o *Operation) GetResponses() *Responses

GetResponses returns the value of the Responses field. Returns nil if not set.

func (*Operation) GetSecurity

func (o *Operation) GetSecurity() []*SecurityRequirement

GetSecurity returns the value of the Security field. Returns nil if not set.

func (*Operation) GetServers

func (o *Operation) GetServers() []*Server

GetServers returns the value of the Servers field. Returns nil if not set.

func (*Operation) GetSummary

func (o *Operation) GetSummary() string

GetSummary returns the value of the Summary field. Returns empty string if not set.

func (*Operation) GetTags

func (o *Operation) GetTags() []string

GetTags returns the value of the Tags field. Returns nil if not set.

func (*Operation) IsDeprecated

func (o *Operation) IsDeprecated() bool

IsDeprecated is an alias for GetDeprecated for backward compatibility. Deprecated: Use GetDeprecated instead for consistency with other models.

func (*Operation) Validate

func (o *Operation) Validate(ctx context.Context, opts ...validation.Option) []error

Validate validates the Operation object against the OpenAPI Specification.

type OptimizeNameCallback added in v1.6.0

type OptimizeNameCallback func(suggestedName string, hash string, locations []string, schema *oas3.JSONSchema[oas3.Referenceable]) string

OptimizeNameCallback is a callback function that receives information about a new component being created and returns the name to use for that component.

Parameters:

  • suggestedName: The suggested name (e.g., "Schema_abc123def")
  • hash: The hash of the schema content
  • locations: Array of JSON pointers to where the inline schemas were found
  • schema: The JSON schema that will be turned into a component

Returns:

  • The name to use for the new component

type Option

type Option[T any] func(o *T)

func WithSkipValidation

func WithSkipValidation() Option[UnmarshalOptions]

WithSkipValidation will skip validation of the OpenAPI document during unmarshaling. Useful to quickly load a document that will be mutated and validated later.

func WithUpgradeSamePatchVersion

func WithUpgradeSamePatchVersion() Option[UpgradeOptions]

WithUpgradeSamePatchVersion will upgrade the same patch version of the OpenAPI document. For example 3.1.0 to 3.1.1.

type Parameter

type Parameter struct {
	marshaller.Model[core.Parameter]

	// Name is the case sensitive name of the parameter.
	Name string
	// In is the location of the parameter. One of "query", "header", "path" or "cookie".
	In ParameterIn
	// Description is a brief description of the parameter. May contain CommonMark syntax.
	Description *string
	// Required determines whether this parameter is mandatory. If the parameter location is "path", this property is REQUIRED and its value MUST be true.
	Required *bool
	// Deprecated describes whether this parameter is deprecated.
	Deprecated *bool
	// AllowEmptyValue determines if empty values are allowed for query parameters.
	AllowEmptyValue *bool
	// Style determines the serialization style of the parameter.
	Style *SerializationStyle
	// Explode determines for array and object values whether separate parameters should be generated for each item in the array or object.
	Explode *bool
	// AllowReserved determines if the value of this parameter can contain reserved characters as defined by RFC3986.
	AllowReserved *bool
	// Schema is the schema defining the type used for the parameter. Mutually exclusive with Content.
	Schema *oas3.JSONSchema[oas3.Referenceable]
	// Content represents the content type and schema of a parameter. Mutually exclusive with Schema.
	Content *sequencedmap.Map[string, *MediaType]
	// Example is an example of the parameter's value. Mutually exclusive with Examples.
	Example values.Value
	// Examples is a map of examples of the parameter's value. Mutually exclusive with Example.
	Examples *sequencedmap.Map[string, *ReferencedExample]
	// Extensions provides a list of extensions to the Parameter object.
	Extensions *extensions.Extensions
}

Parameter represents a single parameter to be included in a request.

func (*Parameter) GetAllowEmptyValue

func (p *Parameter) GetAllowEmptyValue() bool

GetAllowEmptyValue returns the value of the AllowEmptyValue field. False by default if not set.

func (*Parameter) GetAllowReserved

func (p *Parameter) GetAllowReserved() bool

GetAllowReserved returns the value of the AllowReserved field. False by default if not set.

func (*Parameter) GetContent

func (p *Parameter) GetContent() *sequencedmap.Map[string, *MediaType]

GetContent returns the value of the Content field. Returns nil if not set.

func (*Parameter) GetDeprecated

func (p *Parameter) GetDeprecated() bool

GetDeprecated returns the value of the Deprecated field. False by default if not set.

func (*Parameter) GetDescription

func (p *Parameter) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Parameter) GetExample

func (p *Parameter) GetExample() values.Value

GetExample returns the value of the Example field. Returns nil if not set.

func (*Parameter) GetExamples

func (p *Parameter) GetExamples() *sequencedmap.Map[string, *ReferencedExample]

GetExamples returns the value of the Examples field. Returns nil if not set.

func (*Parameter) GetExplode

func (p *Parameter) GetExplode() bool

GetExplode returns the value of the Explode field. When style is "form" default is true otherwise false.

func (*Parameter) GetExtensions

func (p *Parameter) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Parameter) GetIn

func (p *Parameter) GetIn() ParameterIn

GetIn returns the value of the In field. Returns empty ParameterIn if not set.

func (*Parameter) GetName

func (p *Parameter) GetName() string

GetName returns the value of the Name field. Returns empty string if not set.

func (*Parameter) GetRequired

func (p *Parameter) GetRequired() bool

GetRequired returns the value of the Required field. False by default if not set.

func (*Parameter) GetSchema

func (p *Parameter) GetSchema() *oas3.JSONSchema[oas3.Referenceable]

GetSchema returns the value of the Schema field. Returns nil if not set.

func (*Parameter) GetStyle

func (p *Parameter) GetStyle() SerializationStyle

GetStyle returns the value of the Style field. Defaults determined by the In field.

Defaults:

  • ParameterInQuery: SerializationStyleForm
  • ParameterInHeader: SerializationStyleSimple
  • ParameterInPath: SerializationStyleSimple
  • ParameterInCookie: SerializationStyleForm

func (*Parameter) Validate

func (p *Parameter) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Parameter object against the OpenAPI Specification.

type ParameterIn

type ParameterIn string

ParameterIn represents the location of a parameter that is passed in the request.

const (
	// ParameterInQuery represents the location of a parameter that is passed in the query string.
	ParameterInQuery ParameterIn = "query"
	// ParameterInHeader represents the location of a parameter that is passed in the header.
	ParameterInHeader ParameterIn = "header"
	// ParameterInPath represents the location of a parameter that is passed in the path.
	ParameterInPath ParameterIn = "path"
	// ParameterInCookie represents the location of a parameter that is passed in the cookie.
	ParameterInCookie ParameterIn = "cookie"
)

func (ParameterIn) String

func (p ParameterIn) String() string

type PathItem

type PathItem struct {
	marshaller.Model[core.PathItem]
	sequencedmap.Map[HTTPMethod, *Operation]

	// Summary is a short summary of the path and its operations.
	Summary *string
	// Description is a description of the path and its operations. May contain CommonMark syntax.
	Description *string

	// Servers are a list of servers that can be used by the operations represented by this path. Overrides servers defined at the root level.
	Servers []*Server
	// Parameters are a list of parameters that can be used by the operations represented by this path.
	Parameters []*ReferencedParameter

	// Extensions provides a list of extensions to the PathItem object.
	Extensions *extensions.Extensions
}

PathItem represents the available operations for a specific endpoint path. PathItem embeds sequencedmap.Map[HTTPMethod, *Operation] so all map operations are supported for working with HTTP methods.

func NewPathItem

func NewPathItem() *PathItem

NewPathItem creates a new PathItem object with the embedded map initialized.

func (*PathItem) Delete

func (p *PathItem) Delete() *Operation

Delete returns the DELETE operation for this path item.

func (*PathItem) Get

func (p *PathItem) Get() *Operation

Get returns the GET operation for this path item.

func (*PathItem) GetDescription

func (p *PathItem) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*PathItem) GetExtensions

func (p *PathItem) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*PathItem) GetOperation

func (p *PathItem) GetOperation(method HTTPMethod) *Operation

GetOperation returns the operation for the specified HTTP method.

func (*PathItem) GetParameters

func (p *PathItem) GetParameters() []*ReferencedParameter

GetParameters returns the value of the Parameters field. Returns nil if not set.

func (*PathItem) GetServers

func (p *PathItem) GetServers() []*Server

GetServers returns the value of the Servers field. Returns nil if not set.

func (*PathItem) GetSummary

func (p *PathItem) GetSummary() string

GetSummary returns the value of the Summary field. Returns empty string if not set.

func (*PathItem) Head

func (p *PathItem) Head() *Operation

Head returns the HEAD operation for this path item.

func (*PathItem) Options

func (p *PathItem) Options() *Operation

Options returns the OPTIONS operation for this path item.

func (*PathItem) Patch

func (p *PathItem) Patch() *Operation

Patch returns the PATCH operation for this path item.

func (*PathItem) Post

func (p *PathItem) Post() *Operation

Post returns the POST operation for this path item.

func (*PathItem) Put

func (p *PathItem) Put() *Operation

Put returns the PUT operation for this path item.

func (*PathItem) Trace

func (p *PathItem) Trace() *Operation

Trace returns the TRACE operation for this path item.

func (*PathItem) Validate

func (p *PathItem) Validate(ctx context.Context, opts ...validation.Option) []error

Validate validates the PathItem object according to the OpenAPI specification.

type Paths

type Paths struct {
	marshaller.Model[core.Paths]
	sequencedmap.Map[string, *ReferencedPathItem]

	// Extensions provides a list of extensions to the Paths object.
	Extensions *extensions.Extensions
}

Paths is a map of relative endpoint paths to their corresponding PathItem objects. Paths embeds sequencedmap.Map[string, *ReferencedPathItem] so all map operations are supported.

func NewPaths

func NewPaths() *Paths

NewPaths creates a new Paths object with the embedded map initialized.

func (*Paths) GetExtensions

func (p *Paths) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Paths) Validate

func (p *Paths) Validate(ctx context.Context, opts ...validation.Option) []error

Validate validates the Paths object according to the OpenAPI specification.

type Reference

type Reference[T any, V interfaces.Validator[T], C marshaller.CoreModeler] struct {
	marshaller.Model[core.Reference[C]]

	// Reference is the URI to the
	Reference *references.Reference

	// A short summary of the referenced object. Should override any summary provided in the referenced object.
	Summary *string
	// A longer description of the referenced object. Should override any description provided in the referenced object.
	Description *string

	// If this was an inline object instead of a reference this will contain that object.
	Object *T
	// contains filtered or unexported fields
}

func (*Reference[T, V, C]) GetDescription

func (r *Reference[T, V, C]) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Reference[T, V, C]) GetNavigableNode

func (r *Reference[T, V, C]) GetNavigableNode() (any, error)

func (*Reference[T, V, C]) GetObject

func (r *Reference[T, V, C]) GetObject() *T

GetObject returns the referenced object. If this is a reference and its unresolved, this will return nil. This methods is identical to GetResolvedObject but was kept for backwards compatibility

func (*Reference[T, V, C]) GetObjectAny added in v1.6.0

func (r *Reference[T, V, C]) GetObjectAny() any

GetObjectAny returns the referenced object. If this is a reference and its unresolved, this will return nil. This is a convenience method for use with the various reflection based utility functions.

func (*Reference[T, V, C]) GetParent

func (r *Reference[T, V, C]) GetParent() *Reference[T, V, C]

GetParent returns the immediate parent reference if this reference was resolved via a reference chain.

Returns nil if: - This reference was not resolved via a reference (accessed directly) - This reference is the top-level reference in a chain - The reference was accessed by iterating through document components rather than reference resolution

Example: main.yaml -> external.yaml#/Parameter -> Parameter object The intermediate external.yaml reference's GetParent() returns the original main.yaml reference.

func (*Reference[T, V, C]) GetReference

func (r *Reference[T, V, C]) GetReference() references.Reference

GetReference returns the value of the Reference field. Returns empty string if not set.

func (*Reference[T, V, C]) GetReferenceResolutionInfo added in v1.6.0

func (r *Reference[T, V, C]) GetReferenceResolutionInfo() *references.ResolveResult[Reference[T, V, C]]

func (*Reference[T, V, C]) GetResolvedObject added in v1.6.2

func (r *Reference[T, V, C]) GetResolvedObject() *T

GetResolvedObject will return the referenced object. If this is a reference and its unresolved, this will return nil. This methods is identical to GetObject but was added to support the Resolvable interface

func (*Reference[T, V, C]) GetSummary

func (r *Reference[T, V, C]) GetSummary() string

GetSummary returns the value of the Summary field. Returns empty string if not set.

func (*Reference[T, V, C]) GetTopLevelParent

func (r *Reference[T, V, C]) GetTopLevelParent() *Reference[T, V, C]

GetTopLevelParent returns the top-level parent reference if this reference was resolved via a reference chain.

Returns nil if: - This reference was not resolved via a reference (accessed directly) - This reference is already the top-level reference - The reference was accessed by iterating through document components rather than reference resolution

Example: main.yaml -> external.yaml#/Param -> chained.yaml#/Param -> final Parameter object The intermediate references' GetTopLevelParent() returns the original main.yaml reference.

func (*Reference[T, V, C]) IsReference

func (r *Reference[T, V, C]) IsReference() bool

IsReference returns true if the reference is a reference (via $ref) to an object as opposed to an inline object.

func (*Reference[T, V, C]) IsResolved

func (r *Reference[T, V, C]) IsResolved() bool

IsResolved returns true if the reference is resolved (not a reference or the reference has been resolved)

func (*Reference[T, V, C]) MustGetObject

func (r *Reference[T, V, C]) MustGetObject() *T

MustGetObject will return the referenced object. If this is a reference and its unresolved, this will panic. Useful if references have been resolved before hand.

func (*Reference[T, V, C]) Populate

func (r *Reference[T, V, C]) Populate(source any) error

func (*Reference[T, V, C]) Resolve

func (r *Reference[T, V, C]) Resolve(ctx context.Context, opts ResolveOptions) ([]error, error)

Resolve will fully resolve the reference. This will recursively resolve any intermediate references as well. Will return errors if there is a circular reference issue. Validation errors can be skipped by setting the skipValidation flag to true. This will skip the missing field errors that occur during unmarshaling. Resolution doesn't run the Validate function on the resolved object. So if you want to fully validate the object after resolution, you need to call the Validate function manually.

func (*Reference[T, V, C]) SetParent

func (r *Reference[T, V, C]) SetParent(parent *Reference[T, V, C])

SetParent sets the immediate parent reference for this reference. This is a public API for manually constructing reference chains.

Use this when you need to manually establish parent-child relationships between references, typically when creating reference chains programmatically rather than through the normal resolution process.

func (*Reference[T, V, C]) SetTopLevelParent

func (r *Reference[T, V, C]) SetTopLevelParent(topLevelParent *Reference[T, V, C])

SetTopLevelParent sets the top-level parent reference for this reference. This is a public API for manually constructing reference chains.

Use this when you need to manually establish the root of a reference chain, typically when creating reference chains programmatically rather than through the normal resolution process.

func (*Reference[T, V, C]) Validate

func (r *Reference[T, V, C]) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the reusable object against the Arazzo specification.

type ReferencedCallback

type ReferencedCallback = Reference[Callback, *Callback, *core.Callback]

ReferencedCallback represents a callback that can either be referenced from elsewhere or declared inline.

func NewReferencedCallbackFromCallback added in v1.2.0

func NewReferencedCallbackFromCallback(callback *Callback) *ReferencedCallback

NewReferencedCallbackFromCallback creates a new ReferencedCallback from a Callback.

func NewReferencedCallbackFromRef added in v1.2.0

func NewReferencedCallbackFromRef(ref references.Reference) *ReferencedCallback

NewReferencedCallbackFromRef creates a new ReferencedCallback from a reference.

type ReferencedExample

type ReferencedExample = Reference[Example, *Example, *core.Example]

ReferencedExample represents an example that can either be referenced from elsewhere or declared inline.

func NewReferencedExampleFromExample added in v1.2.0

func NewReferencedExampleFromExample(example *Example) *ReferencedExample

NewReferencedExampleFromExample creates a new ReferencedExample from an Example.

func NewReferencedExampleFromRef added in v1.2.0

func NewReferencedExampleFromRef(ref references.Reference) *ReferencedExample

NewReferencedExampleFromRef creates a new ReferencedExample from a reference.

type ReferencedHeader

type ReferencedHeader = Reference[Header, *Header, *core.Header]

ReferencedHeader represents a header that can either be referenced from elsewhere or declared inline.

func NewReferencedHeaderFromHeader added in v1.2.0

func NewReferencedHeaderFromHeader(header *Header) *ReferencedHeader

NewReferencedHeaderFromHeader creates a new ReferencedHeader from a Header.

func NewReferencedHeaderFromRef added in v1.2.0

func NewReferencedHeaderFromRef(ref references.Reference) *ReferencedHeader

NewReferencedHeaderFromRef creates a new ReferencedHeader from a reference.

type ReferencedLink = Reference[Link, *Link, *core.Link]

ReferencedLink represents a link that can either be referenced from elsewhere or declared inline.

func NewReferencedLinkFromLink(link *Link) *ReferencedLink

NewReferencedLinkFromLink creates a new ReferencedLink from a Link.

func NewReferencedLinkFromRef added in v1.2.0

func NewReferencedLinkFromRef(ref references.Reference) *ReferencedLink

NewReferencedLinkFromRef creates a new ReferencedLink from a reference.

type ReferencedObject

type ReferencedObject[T any] interface {
	IsReference() bool
	GetObject() *T
}

type ReferencedParameter

type ReferencedParameter = Reference[Parameter, *Parameter, *core.Parameter]

ReferencedParameter represents a parameter that can either be referenced from elsewhere or declared inline.

func NewReferencedParameterFromParameter added in v1.2.0

func NewReferencedParameterFromParameter(parameter *Parameter) *ReferencedParameter

NewReferencedParameterFromParameter creates a new ReferencedParameter from a Parameter.

func NewReferencedParameterFromRef added in v1.2.0

func NewReferencedParameterFromRef(ref references.Reference) *ReferencedParameter

NewReferencedParameterFromRef creates a new ReferencedParameter from a reference.

type ReferencedPathItem

type ReferencedPathItem = Reference[PathItem, *PathItem, *core.PathItem]

ReferencedPathItem represents a path item that can either be referenced from elsewhere or declared inline.

func NewReferencedPathItemFromPathItem added in v1.2.0

func NewReferencedPathItemFromPathItem(pathItem *PathItem) *ReferencedPathItem

NewReferencedPathItemFromPathItem creates a new ReferencedPathItem from a PathItem.

func NewReferencedPathItemFromRef added in v1.2.0

func NewReferencedPathItemFromRef(ref references.Reference) *ReferencedPathItem

NewReferencedPathItemFromRef creates a new ReferencedPathItem from a reference.

type ReferencedRequestBody

type ReferencedRequestBody = Reference[RequestBody, *RequestBody, *core.RequestBody]

ReferencedRequestBody represents a request body that can either be referenced from elsewhere or declared inline.

func NewReferencedRequestBodyFromRef added in v1.2.0

func NewReferencedRequestBodyFromRef(ref references.Reference) *ReferencedRequestBody

NewReferencedRequestBodyFromRef creates a new ReferencedRequestBody from a reference.

func NewReferencedRequestBodyFromRequestBody added in v1.2.0

func NewReferencedRequestBodyFromRequestBody(requestBody *RequestBody) *ReferencedRequestBody

NewReferencedRequestBodyFromRequestBody creates a new ReferencedRequestBody from a RequestBody.

type ReferencedResponse

type ReferencedResponse = Reference[Response, *Response, *core.Response]

ReferencedResponse represents a response that can either be referenced from elsewhere or declared inline.

func NewReferencedResponseFromRef added in v1.2.0

func NewReferencedResponseFromRef(ref references.Reference) *ReferencedResponse

NewReferencedResponseFromRef creates a new ReferencedResponse from a reference.

func NewReferencedResponseFromResponse added in v1.2.0

func NewReferencedResponseFromResponse(response *Response) *ReferencedResponse

NewReferencedResponseFromResponse creates a new ReferencedResponse from a Response.

type ReferencedSecurityScheme

type ReferencedSecurityScheme = Reference[SecurityScheme, *SecurityScheme, *core.SecurityScheme]

ReferencedSecurityScheme represents a security scheme that can either be referenced from elsewhere or declared inline.

func NewReferencedSecuritySchemeFromRef added in v1.2.0

func NewReferencedSecuritySchemeFromRef(ref references.Reference) *ReferencedSecurityScheme

NewReferencedSecuritySchemeFromRef creates a new ReferencedSecurityScheme from a reference.

func NewReferencedSecuritySchemeFromSecurityScheme added in v1.2.0

func NewReferencedSecuritySchemeFromSecurityScheme(securityScheme *SecurityScheme) *ReferencedSecurityScheme

NewReferencedSecuritySchemeFromSecurityScheme creates a new ReferencedSecurityScheme from a SecurityScheme.

type RequestBody

type RequestBody struct {
	marshaller.Model[core.RequestBody]

	// Description is a description of the request body. May contain CommonMark syntax.
	Description *string
	// Content is a map of content types to the schema that describes them that the operation accepts.
	Content *sequencedmap.Map[string, *MediaType]
	// Required determines whether this request body is mandatory.
	Required *bool

	// Extensions provides a list of extensions to the RequestBody object.
	Extensions *extensions.Extensions
}

func (*RequestBody) GetContent

func (r *RequestBody) GetContent() *sequencedmap.Map[string, *MediaType]

GetContent returns the value of the Content field. Returns nil if not set.

func (*RequestBody) GetDescription

func (r *RequestBody) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*RequestBody) GetRequired

func (r *RequestBody) GetRequired() bool

GetRequired returns the value of the Required field. False by default if not set.

func (*RequestBody) Validate

func (r *RequestBody) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the RequestBody object against the OpenAPI Specification.

type ResolveAllOptions

type ResolveAllOptions struct {
	// OpenAPILocation is the location of the OpenAPI document to resolve.
	OpenAPILocation string
	// DisableExternalRefs when set to true will disable resolving of external references and return an error instead.
	DisableExternalRefs bool
	// VirtualFS is an optional virtual file system that will be used for any file based references. If not provided normal file system operations will be used.
	VirtualFS system.VirtualFS
	// HTTPClient is an optional HTTP client that will be used for any HTTP based references. If not provided http.DefaultClient will be used.
	HTTPClient system.Client
}

ResolveAllOptions represents the options available when resolving all references in an OpenAPI document.

type ResolveOptions

type ResolveOptions = references.ResolveOptions

ResolveOptions represent the options available when resolving a reference.

type Response

type Response struct {
	marshaller.Model[core.Response]

	// Description is a description of the response. May contain CommonMark syntax.
	Description string
	// Headers is a map of headers that are sent with the response.
	Headers *sequencedmap.Map[string, *ReferencedHeader]
	// Content is a map of content types to the schema that describes them.
	Content *sequencedmap.Map[string, *MediaType]
	// Links is a map of operations links that can be followed from the response.
	Links *sequencedmap.Map[string, *ReferencedLink]

	// Extensions provides a list of extensions to the Response object.
	Extensions *extensions.Extensions
}

Response represents a single response from an API Operation.

func (*Response) GetContent

func (r *Response) GetContent() *sequencedmap.Map[string, *MediaType]

GetContent returns the value of the Content field. Returns nil if not set.

func (*Response) GetDescription

func (r *Response) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Response) GetExtensions

func (r *Response) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Response) GetHeaders

func (r *Response) GetHeaders() *sequencedmap.Map[string, *ReferencedHeader]

GetHeaders returns the value of the Headers field. Returns nil if not set.

func (r *Response) GetLinks() *sequencedmap.Map[string, *ReferencedLink]

GetLinks returns the value of the Links field. Returns nil if not set.

func (*Response) Validate

func (r *Response) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Response object according to the OpenAPI specification.

type Responses

type Responses struct {
	marshaller.Model[core.Responses]
	sequencedmap.Map[string, *ReferencedResponse]

	// Default represents the remaining responses not declared in the map.
	Default *ReferencedResponse

	// Extensions provides a list of extensions to the Responses object.
	Extensions *extensions.Extensions
}

func NewResponses

func NewResponses(elements ...*sequencedmap.Element[string, *ReferencedResponse]) *Responses

NewResponses creates a new Responses instance with an initialized map.

func (*Responses) GetDefault

func (r *Responses) GetDefault() *ReferencedResponse

GetDefault returns the value of the Default field. Returns nil if not set.

func (*Responses) GetExtensions

func (r *Responses) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Responses) Populate

func (r *Responses) Populate(source any) error

func (*Responses) Validate

func (r *Responses) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Responses object according to the OpenAPI specification.

type SecurityRequirement

type SecurityRequirement struct {
	marshaller.Model[core.SecurityRequirement]
	sequencedmap.Map[string, []string]
}

SecurityRequirement represents a security requirement for an API or operation. Each name in the map represents a security scheme that can be used to secure the API or operation. If the security scheme is of type "oauth2" or "openIdConnect", then the value is a list of scope names required by the operation. SecurityRequirement embeds sequencedmap.Map[string, []string] so all map operations are supported.

func NewSecurityRequirement

func NewSecurityRequirement(elems ...*sequencedmap.Element[string, []string]) *SecurityRequirement

NewSecurityRequirement creates a new SecurityRequirement object with the embedded map initialized.

func (*SecurityRequirement) Populate

func (s *SecurityRequirement) Populate(source any) error

func (*SecurityRequirement) Validate

func (s *SecurityRequirement) Validate(ctx context.Context, opts ...validation.Option) []error

Validate validates the SecurityRequirement object according to the OpenAPI specification.

type SecuritySchemaType

type SecuritySchemaType string
const (
	SecuritySchemeTypeAPIKey        SecuritySchemaType = "apiKey"
	SecuritySchemeTypeHTTP          SecuritySchemaType = "http"
	SecuritySchemeTypeMutualTLS     SecuritySchemaType = "mutualTLS"
	SecuritySchemeTypeOAuth2        SecuritySchemaType = "oauth2"
	SecuritySchemeTypeOpenIDConnect SecuritySchemaType = "openIdConnect"
)

func (SecuritySchemaType) String

func (s SecuritySchemaType) String() string

type SecurityScheme

type SecurityScheme struct {
	marshaller.Model[core.SecurityScheme]

	// Type represents the type of the security scheme.
	Type SecuritySchemaType
	// Description is a description of the security scheme.
	Description *string
	// Name is the name of the header, query or cookie parameter to be used.
	Name *string
	// In is the location of the API key.
	In *SecuritySchemeIn
	// Scheme is the name of the HTTP Authorization scheme to be used in the Authorization header.
	Scheme *string
	// BearerFormat is the name of the HTTP Authorization scheme to be used in the Authorization header.
	BearerFormat *string
	// Flows is a map of the different flows supported by the OAuth2 security scheme.
	Flows *OAuthFlows
	// OpenIdConnectUrl is a URL to discover OAuth2 configuration values.
	OpenIdConnectUrl *string
	// Extensions provides a list of extensions to the SecurityScheme object.
	Extensions *extensions.Extensions
}

func (*SecurityScheme) GetBearerFormat

func (s *SecurityScheme) GetBearerFormat() string

GetBearerFormat returns the value of the BearerFormat field. Returns empty string if not set.

func (*SecurityScheme) GetDescription

func (s *SecurityScheme) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*SecurityScheme) GetExtensions

func (s *SecurityScheme) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*SecurityScheme) GetFlows

func (s *SecurityScheme) GetFlows() *OAuthFlows

GetFlows returns the value of the Flows field. Returns nil if not set.

func (*SecurityScheme) GetIn

func (s *SecurityScheme) GetIn() SecuritySchemeIn

GetIn returns the value of the In field. Returns empty SecuritySchemeIn if not set.

func (*SecurityScheme) GetName

func (s *SecurityScheme) GetName() string

GetName returns the value of the Name field. Returns empty string if not set.

func (*SecurityScheme) GetOpenIdConnectUrl

func (s *SecurityScheme) GetOpenIdConnectUrl() string

GetOpenIdConnectUrl returns the value of the OpenIdConnectUrl field. Returns empty string if not set.

func (*SecurityScheme) GetScheme

func (s *SecurityScheme) GetScheme() string

GetScheme returns the value of the Scheme field. Returns empty string if not set.

func (*SecurityScheme) GetType

func (s *SecurityScheme) GetType() SecuritySchemaType

GetType returns the value of the Type field. Returns empty SecuritySchemaType if not set.

func (*SecurityScheme) Validate

func (s *SecurityScheme) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the SecurityScheme object against the OpenAPI Specification.

type SecuritySchemeIn

type SecuritySchemeIn string
const (
	SecuritySchemeInHeader SecuritySchemeIn = "header"
	SecuritySchemeInQuery  SecuritySchemeIn = "query"
	SecuritySchemeInCookie SecuritySchemeIn = "cookie"
)

func (SecuritySchemeIn) String

func (s SecuritySchemeIn) String() string

type SerializationStyle

type SerializationStyle string

SerializationStyle represents the serialization style of a parameter.

const (
	// SerializationStyleSimple represents simple serialization as defined by RFC 6570. Valid for path, header parameters.
	SerializationStyleSimple SerializationStyle = "simple"
	// SerializationStyleForm represents form serialization as defined by RFC 6570. Valid for query, cookie parameters.
	SerializationStyleForm SerializationStyle = "form"
	// SerializationStyleLabel represents label serialization as defined by RFC 6570. Valid for path parameters.
	SerializationStyleLabel SerializationStyle = "label"
	// SerializationStyleMatrix represents matrix serialization as defined by RFC 6570. Valid for path parameters.
	SerializationStyleMatrix SerializationStyle = "matrix"
	// SerializationStyleSpaceDelimited represents space-delimited serialization. Valid for query parameters.
	SerializationStyleSpaceDelimited SerializationStyle = "spaceDelimited"
	// SerializationStylePipeDelimited represents pipe-delimited serialization. Valid for query parameters.
	SerializationStylePipeDelimited SerializationStyle = "pipeDelimited"
	// SerializationStyleDeepObject represents deep object serialization for rendering nested objects using form parameters. Valid for query parameters.
	SerializationStyleDeepObject SerializationStyle = "deepObject"
)

func (SerializationStyle) String

func (s SerializationStyle) String() string

type Server

type Server struct {
	marshaller.Model[core.Server]

	// A URL to a server capable of providing the functionality described in the API.
	// The URL supports Server Variables and may be absolute or relative to where the OpenAPI document is located.
	URL string
	// A description of the server. May contain CommonMark syntax.
	Description *string
	// A map of variables available to be templated into the URL.
	Variables *sequencedmap.Map[string, *ServerVariable]

	// Extensions provides a list of extensions to the Server object.
	Extensions *extensions.Extensions
}

Server represents a server available to provide the functionality described in the API.

func (*Server) GetDescription

func (s *Server) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Server) GetExtensions

func (s *Server) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Server) GetURL

func (s *Server) GetURL() string

GetURL returns the value of the URL field. Returns empty string if not set.

func (*Server) GetVariables

func (s *Server) GetVariables() *sequencedmap.Map[string, *ServerVariable]

GetVariables returns the value of the Variables field. Returns nil if not set.

func (*Server) Validate

func (s *Server) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Server object against the OpenAPI Specification.

type ServerVariable

type ServerVariable struct {
	marshaller.Model[core.ServerVariable]

	// The default value to use for substitution. If none is provided by the end-user.
	Default string
	// A restricted set of allowed values if provided.
	Enum []string
	// A description of the variable.
	Description *string

	// Extensions provides a list of extensions to the ServerVariable object.
	Extensions *extensions.Extensions
}

ServerVariable represents a variable available to be templated in the associated Server's URL.

func (*ServerVariable) GetDefault

func (v *ServerVariable) GetDefault() string

GetDefault returns the value of the Default field. Returns empty string if not set.

func (*ServerVariable) GetDescription

func (v *ServerVariable) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*ServerVariable) GetEnum

func (v *ServerVariable) GetEnum() []string

GetEnum returns the value of the Enum field. Returns nil if not set.

func (*ServerVariable) Validate

func (v *ServerVariable) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the ServerVariable object against the OpenAPI Specification.

type Tag

type Tag struct {
	marshaller.Model[core.Tag]

	// The name of the tag.
	Name string
	// A description for the tag. May contain CommonMark syntax.
	Description *string
	// External documentation for this tag.
	ExternalDocs *oas3.ExternalDocumentation

	// Extensions provides a list of extensions to the Tag object.
	Extensions *extensions.Extensions
}

Tag represent the metadata for a single tag relating to operations in the API.

func (*Tag) GetDescription

func (t *Tag) GetDescription() string

GetDescription returns the value of the Description field. Returns empty string if not set.

func (*Tag) GetExtensions

func (t *Tag) GetExtensions() *extensions.Extensions

GetExtensions returns the value of the Extensions field. Returns an empty extensions map if not set.

func (*Tag) GetExternalDocs

func (t *Tag) GetExternalDocs() *oas3.ExternalDocumentation

GetExternalDocs returns the value of the ExternalDocs field. Returns nil if not set.

func (*Tag) GetName

func (t *Tag) GetName() string

GetName returns the value of the Name field. Returns empty string if not set.

func (*Tag) Validate

func (t *Tag) Validate(ctx context.Context, opts ...validation.Option) []error

Validate will validate the Tag object against the OpenAPI Specification.

type UnmarshalOptions

type UnmarshalOptions struct {
	// contains filtered or unexported fields
}

type UpgradeOptions

type UpgradeOptions struct {
	// contains filtered or unexported fields
}

type WalkItem

type WalkItem struct {
	Match    MatchFunc
	Location Locations
	OpenAPI  *OpenAPI
}

WalkItem represents a single item yielded by the Walk iterator.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL