### Install libopenapi-validator Source: https://github.com/pb33f/libopenapi-validator/blob/main/README.md Use this command to add the libopenapi-validator package to your Go project. ```bash go get github.com/pb33f/libopenapi-validator ``` -------------------------------- ### Install Pre-commit Hook Source: https://github.com/pb33f/libopenapi-validator/blob/main/README.md Execute this command to integrate the validator with your Git pre-commit hooks. ```bash pre-commit install ``` -------------------------------- ### Create Validator with Configuration Options Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Create a validator with various configuration options using the functional options pattern. Options include format assertions, security validation, strict mode, and custom regex caches. ```go package main import ( "log/slog" "os" "sync" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" "github.com/pb33f/libopenapi-validator/config" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) // Create validator with multiple configuration options docValidator, errs := validator.NewValidator(document, // Enable format assertions (date, date-time, uuid, etc.) config.WithFormatAssertions(), // Enable content assertions (contentType, contentEncoding) config.WithContentAssertions(), // Disable security validation config.WithoutSecurityValidation(), // Enable strict mode to catch undeclared properties config.WithStrictMode(), // Set paths to ignore in strict validation config.WithStrictIgnorePaths("$.body.metadata.*", "$.body.**.x-*"), // Enable XML body validation config.WithXmlBodyValidation(), // Enable URL-encoded body validation config.WithURLEncodedBodyValidation(), // Enable scalar coercion (string->boolean/number) config.WithScalarCoercion(), // Add custom regex cache config.WithRegexCache(&sync.Map{}), // Add logger for debug output config.WithLogger(slog.New(slog.NewJSONHandler(os.Stdout, nil))), ) if errs != nil { panic(errs) } _ = docValidator } ``` -------------------------------- ### Implement HTTP Validation Middleware in Go Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Demonstrates creating a custom HTTP middleware that uses the libopenapi-validator to intercept and validate incoming requests. Requires an initialized validator instance and returns a 400 Bad Request response with JSON-encoded validation errors upon failure. ```go package main import ( "encoding/json" "log" "net/http" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func ValidationMiddleware(docValidator validator.Validator) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Validate the incoming request valid, errs := docValidator.ValidateHttpRequest(r) if !valid { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusBadRequest) // Return validation errors as JSON errorResponse := map[string]interface{}{ "errors": make([]map[string]interface{}, len(errs)), } for i, e := range errs { errorResponse["errors"].([]map[string]interface{})[i] = map[string]interface{}{ "message": e.Message, "reason": e.Reason, "type": e.ValidationType, "howToFix": e.HowToFix, } } json.NewEncoder(w).Encode(errorResponse) return } next.ServeHTTP(w, r) }) } } func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Create handler handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) }) // Wrap with validation middleware validatedHandler := ValidationMiddleware(docValidator)(handler) log.Println("Server starting on :8080") http.ListenAndServe(":8080", validatedHandler) } ``` -------------------------------- ### Implement Custom Schema Cache Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Define a custom cache by implementing the SchemaCache interface to manage memory or TTL-based expiration. ```go package main import ( "os" "sync" "time" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" "github.com/pb33f/libopenapi-validator/cache" "github.com/pb33f/libopenapi-validator/config" ) // TTLCache implements cache.SchemaCache with time-to-live expiration type TTLCache struct { mu sync.RWMutex entries map[uint64]*ttlEntry ttl time.Duration } type ttlEntry struct { value *cache.SchemaCacheEntry expiresAt time.Time } func NewTTLCache(ttl time.Duration) *TTLCache { return &TTLCache{ entries: make(map[uint64]*ttlEntry), ttl: ttl, } } func (c *TTLCache) Load(key uint64) (*cache.SchemaCacheEntry, bool) { c.mu.RLock() defer c.mu.RUnlock() entry, ok := c.entries[key] if !ok || time.Now().After(entry.expiresAt) { return nil, false } return entry.value, true } func (c *TTLCache) Store(key uint64, value *cache.SchemaCacheEntry) { c.mu.Lock() defer c.mu.Unlock() c.entries[key] = &ttlEntry{ value: value, expiresAt: time.Now().Add(c.ttl), } } func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) // Use custom TTL cache customCache := NewTTLCache(5 * time.Minute) docValidator, _ := validator.NewValidator(document, config.WithSchemaCache(customCache), ) // Or disable caching entirely noCacheValidator, _ := validator.NewValidator(document, config.WithSchemaCache(nil), ) _ = docValidator _ = noCacheValidator } ``` -------------------------------- ### Validate OpenAPI Document Source: https://github.com/pb33f/libopenapi-validator/blob/main/README.md Run the validator command-line tool to validate an OpenAPI file. Optional flags can modify behavior. ```bash go run github.com/pb33f/libopenapi-validator/cmd/validate@latest [--regexengine] [--yaml2json] ``` -------------------------------- ### Validate OpenAPI Documents via CLI Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Use the command-line interface to validate files with options for regex engines and YAML-to-JSON conversion. ```bash # Install the CLI tool go install github.com/pb33f/libopenapi-validator/cmd/validate@latest # Validate an OpenAPI document validate openapi.yaml # Use ECMAScript regex engine for complex patterns validate --regexengine=ecmascript openapi.yaml # Convert YAML to JSON before validation (handles deeply nested structures) validate --yaml2json openapi.yaml # Combine options validate --regexengine=ecmascript --yaml2json complex-spec.yaml ``` -------------------------------- ### Create Validator from OpenAPI Document Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Create a validator instance from a libopenapi Document. This automatically builds a radix tree for path lookup and warms schema caches. ```go package main import ( "fmt" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { // Load the OpenAPI 3+ spec petstore, err := os.ReadFile("openapi.yaml") if err != nil { panic(err) } // Create a new OpenAPI document using libopenapi document, docErrs := libopenapi.NewDocument(petstore) if docErrs != nil { panic(docErrs) } // Create a new validator docValidator, validatorErrs := validator.NewValidator(document) if validatorErrs != nil { panic(validatorErrs) } fmt.Println("Validator created successfully") } ``` -------------------------------- ### Handle Validation Errors in Go Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Iterate through validation errors to access detailed metadata, spec locations, and schema-specific issues. ```go package main import ( "encoding/json" "fmt" "net/http" "os" "strings" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Invalid request body := `{"invalid": "data"}` request, _ := http.NewRequest(http.MethodPost, "/pet", strings.NewReader(body)) request.Header.Set("Content-Type", "application/json") valid, validationErrs := docValidator.ValidateHttpRequest(request) if !valid { for _, e := range validationErrs { // Basic error info fmt.Printf("Message: %s\n", e.Message) fmt.Printf("Reason: %s\n", e.Reason) fmt.Printf("Validation Type: %s\n", e.ValidationType) fmt.Printf("Validation SubType: %s\n", e.ValidationSubType) fmt.Printf("How to Fix: %s\n", e.HowToFix) // Location in spec if e.SpecLine > 0 { fmt.Printf("Spec Location: line %d, column %d\n", e.SpecLine, e.SpecCol) } // Request context fmt.Printf("Request Path: %s\n", e.RequestPath) fmt.Printf("Request Method: %s\n", e.RequestMethod) // Check for specific error types if e.IsPathMissingError() { fmt.Println("Path not found in specification") } if e.IsOperationMissingError() { fmt.Println("Operation not defined for this path") } // Schema validation details for _, schemaErr := range e.SchemaValidationErrors { fmt.Printf(" Schema Error:\n") fmt.Printf(" Reason: %s\n", schemaErr.Reason) fmt.Printf(" Field Name: %s\n", schemaErr.FieldName) fmt.Printf(" Field Path: %s\n", schemaErr.FieldPath) fmt.Printf(" Location: line %d, col %d\n", schemaErr.Line, schemaErr.Column) } // Serialize error to JSON errJSON, _ := json.MarshalIndent(e, "", " ") fmt.Printf("Error JSON:\n%s\n", errJSON) } } } ``` -------------------------------- ### Validate with YAML to JSON Conversion Source: https://github.com/pb33f/libopenapi-validator/blob/main/README.md Enable YAML to JSON pre-conversion for validation, which helps bypass limitations with deeply nested or complex YAML structures in OpenAPI specifications. ```bash go run github.com/pb33f/libopenapi-validator/cmd/validate@latest --yaml2json ``` -------------------------------- ### Validate HTTP Request Asynchronously Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Uses goroutines to validate path, query, cookie, header parameters, and request body in parallel. ```go package main import ( "fmt" "net/http" "os" "strings" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Create an HTTP request with JSON body body := `{"name": "fluffy", "photoUrls": ["https://example.com/fluffy.jpg"]}` request, _ := http.NewRequest( http.MethodPost, "/pet", strings.NewReader(body), ) request.Header.Set("Content-Type", "application/json") // Validate the request asynchronously (uses goroutines) valid, validationErrs := docValidator.ValidateHttpRequest(request) if !valid { for _, e := range validationErrs { fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) fmt.Printf("Reason: %s\n", e.Reason) fmt.Printf("How to fix: %s\n", e.HowToFix) if e.SpecLine > 0 { fmt.Printf("Spec location: line %d, column %d\n", e.SpecLine, e.SpecCol) } } } else { fmt.Println("Request is valid!") } } ``` -------------------------------- ### Validate Parameters with ParameterValidator Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Uses the ParameterValidator interface to check path, query, header, and security requirements against an OpenAPI specification. ```go package main import ( "fmt" "net/http" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Get the parameter validator paramValidator := docValidator.GetParameterValidator() // Create request with query parameters request, _ := http.NewRequest( http.MethodGet, "/pet/findByStatus?status=available&status=pending", nil, ) // Validate query parameters valid, errs := paramValidator.ValidateQueryParams(request) if !valid { for _, e := range errs { fmt.Printf("Query param error: %s\n", e.Message) } } // Validate path parameters pathRequest, _ := http.NewRequest(http.MethodGet, "/pet/123", nil) valid, errs = paramValidator.ValidatePathParams(pathRequest) if !valid { for _, e := range errs { fmt.Printf("Path param error: %s\n", e.Message) } } // Validate header parameters headerRequest, _ := http.NewRequest(http.MethodGet, "/pet/123", nil) headerRequest.Header.Set("api_key", "secret-key-123") valid, errs = paramValidator.ValidateHeaderParams(headerRequest) if !valid { for _, e := range errs { fmt.Printf("Header param error: %s\n", e.Message) } } // Validate security requirements valid, errs = paramValidator.ValidateSecurity(headerRequest) if !valid { for _, e := range errs { fmt.Printf("Security error: %s\n", e.Message) } } } ``` -------------------------------- ### Validate HTTP Request Synchronously Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Performs validation without spawning goroutines, ensuring deterministic execution order. ```go package main import ( "fmt" "net/http" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Request with invalid path parameter (should be integer) request, _ := http.NewRequest(http.MethodGet, "/pet/NotAValidPetId", nil) // Validate synchronously (no goroutines) valid, validationErrs := docValidator.ValidateHttpRequestSync(request) if !valid { for _, e := range validationErrs { fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) // Output: Type: parameter, Failure: Path parameter 'petId' is not a valid integer } } } ``` -------------------------------- ### Implement Strict Mode Validation Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Detects undeclared properties in request bodies even when additionalProperties is enabled, useful for API governance. ```go package main import ( "fmt" "net/http" "strings" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" "github.com/pb33f/libopenapi-validator/config" ) func main() { spec := []byte(` openapi: "3.1.0" info: title: Strict API version: "1.0" paths: /users: post: requestBody: required: true content: application/json: schema: type: object properties: name: type: string email: type: string additionalProperties: true responses: '200': description: Success `) document, _ := libopenapi.NewDocument(spec) // Create validator with strict mode enabled docValidator, _ := validator.NewValidator(document, config.WithStrictMode(), // Optionally ignore specific paths config.WithStrictIgnorePaths("$.body.metadata.*", "$.body.**.x-*"), // Add extra ignored headers config.WithStrictIgnoredHeadersExtra("X-Custom-Header"), ) // Request with undeclared property body := `{"name": "John", "email": "john@example.com", "undeclaredField": "value"}` request, _ := http.NewRequest(http.MethodPost, "/users", strings.NewReader(body)) request.Header.Set("Content-Type", "application/json") valid, errs := docValidator.ValidateHttpRequest(request) if !valid { for _, e := range errs { fmt.Printf("Strict mode violation: %s\n", e.Message) fmt.Printf("Reason: %s\n", e.Reason) // Output will report the undeclared "undeclaredField" property } } } ``` -------------------------------- ### Validate OpenAPI Documents in Go Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Ensures an OpenAPI document conforms to the 3.0 or 3.1 specification using the ValidateDocument method. ```go package main import ( "fmt" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { // Load a potentially invalid spec spec, _ := os.ReadFile("invalid_openapi.yaml") document, docErrs := libopenapi.NewDocument(spec) if docErrs != nil { fmt.Printf("Document parsing error: %v\n", docErrs) return } docValidator, _ := validator.NewValidator(document) // Validate the document against the OpenAPI schema valid, validationErrs := docValidator.ValidateDocument() if !valid { for i, e := range validationErrs { fmt.Printf("%d: Type: %s, Failure: %s\n", i, e.ValidationType, e.Message) fmt.Printf("Fix: %s\n\n", e.HowToFix) // Print schema-level errors with line/column info for _, schemaErr := range e.SchemaValidationErrors { fmt.Printf(" - %s (line %d, col %d)\n", schemaErr.Reason, schemaErr.Line, schemaErr.Column) } } } else { fmt.Println("Document is valid!") } } ``` -------------------------------- ### Validate with Custom Regex Engine Source: https://github.com/pb33f/libopenapi-validator/blob/main/README.md Specify a custom regex engine, such as 'ecmascript', for validation. The default is 're2'. ```bash go run github.com/pb33f/libopenapi-validator/cmd/validate@latest --regexengine=ecmascript ``` -------------------------------- ### Validate HTTP Response Headers Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Enforces required headers and schema constraints defined in the OpenAPI specification for a given response. ```go package main import ( "fmt" "net/http" "net/http/httptest" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { spec := []byte(` openapi: "3.0.0" info: title: Test API version: "1.0" paths: /health: get: responses: '200': headers: X-Request-Id: description: Request tracking ID required: true schema: type: string format: uuid X-Rate-Limit: description: Rate limit remaining required: true schema: type: integer description: Health check response `) document, _ := libopenapi.NewDocument(spec) docValidator, _ := validator.NewValidator(document) request, _ := http.NewRequest(http.MethodGet, "/health", nil) // Create response with headers recorder := httptest.NewRecorder() recorder.Header().Set("X-Request-Id", "550e8400-e29b-41d4-a716-446655440000") recorder.Header().Set("X-Rate-Limit", "not-a-number") // Invalid: should be integer recorder.WriteHeader(http.StatusOK) valid, errs := docValidator.ValidateHttpResponse(request, recorder.Result()) if !valid { for _, e := range errs { fmt.Printf("Header validation error: %s\n", e.Message) } } } ``` -------------------------------- ### Validate HTTP Request and Response in Go Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Validates both request and response objects simultaneously using the ValidateHttpRequestResponse method, suitable for contract testing. ```go package main import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "strings" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" "github.com/pb33f/libopenapi-validator/helpers" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Create request reqBody := `{"name": "fluffy", "photoUrls": ["https://example.com/fluffy.jpg"]}` request, _ := http.NewRequest(http.MethodPost, "/pet", strings.NewReader(reqBody)) request.Header.Set("Content-Type", "application/json") // Simulate response recorder := httptest.NewRecorder() handler := func(w http.ResponseWriter, r *http.Request) { w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) w.WriteHeader(http.StatusOK) response := map[string]interface{}{ "id": 1, "name": "fluffy", "photoUrls": []string{"https://example.com/fluffy.jpg"}, } json.NewEncoder(w).Encode(response) } handler(recorder, request) // Validate both request and response valid, validationErrs := docValidator.ValidateHttpRequestResponse(request, recorder.Result()) if !valid { for _, e := range validationErrs { fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) } } else { fmt.Println("Request and response are valid!") } } ``` -------------------------------- ### ValidateHttpRequestSync (Synchronous) Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Validates an HTTP request against the OpenAPI specification synchronously without spawning goroutines. ```APIDOC ## ValidateHttpRequestSync (Synchronous) ### Description Validates an HTTP request synchronously. This is useful for scenarios where deterministic execution order is required. ### Method POST/GET/PUT/DELETE (Any) ### Parameters #### Request Body - **request** (http.Request) - Required - The HTTP request object to validate against the OpenAPI document. ``` -------------------------------- ### ValidateHttpRequest (Asynchronous) Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Validates an HTTP request against the OpenAPI specification asynchronously using goroutines. ```APIDOC ## ValidateHttpRequest (Asynchronous) ### Description Validates an HTTP request (path, query, cookie, header parameters, and request body) against the OpenAPI specification in parallel. ### Method POST/GET/PUT/DELETE (Any) ### Parameters #### Request Body - **request** (http.Request) - Required - The HTTP request object to validate against the OpenAPI document. ``` -------------------------------- ### Validate Data Against Schemas Directly in Go Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Uses the SchemaValidator interface to validate arbitrary data against specific OpenAPI schemas, supporting both 3.0 and 3.1 versions. ```go package main import ( "fmt" "github.com/pb33f/libopenapi" "github.com/pb33f/libopenapi-validator/schema_validation" ) func main() { spec := []byte(` openapi: "3.1.0" info: title: Test API version: "1.0" paths: {} components: schemas: User: type: object required: - name - email properties: name: type: string minLength: 1 email: type: string format: email age: type: integer minimum: 0 `) document, _ := libopenapi.NewDocument(spec) model, _ := document.BuildV3Model() // Get the schema from components userSchema := model.Model.Components.Schemas.GetOrZero("User").Schema() // Create a schema validator schemaValidator := schema_validation.NewSchemaValidator() // Valid payload validPayload := `{"name": "John Doe", "email": "john@example.com", "age": 30}` valid, errs := schemaValidator.ValidateSchemaString(userSchema, validPayload) fmt.Printf("Valid payload: %v\n", valid) // Output: true // Invalid payload (missing required field, invalid age) invalidPayload := `{"email": "invalid-email", "age": -5}` valid, errs = schemaValidator.ValidateSchemaString(userSchema, invalidPayload) if !valid { for _, e := range errs { fmt.Printf("Validation failed: %s\n", e.Message) for _, schemaErr := range e.SchemaValidationErrors { fmt.Printf(" - Field: %s, Error: %s\n", schemaErr.FieldPath, schemaErr.Reason) } } } } ``` -------------------------------- ### Validate HTTP Response Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Validates response body and headers against the expected schema defined in the OpenAPI specification. ```go package main import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" "github.com/pb33f/libopenapi-validator/helpers" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Create request to identify the operation request, _ := http.NewRequest(http.MethodGet, "/pet/findByStatus?status=sold", nil) // Simulate a response recorder := httptest.NewRecorder() handler := func(w http.ResponseWriter, r *http.Request) { w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) w.WriteHeader(http.StatusOK) // Response with invalid data (category.id should be integer, not string) pets := []map[string]interface{}{ { "id": 123, "name": "cotton", "category": map[string]interface{}{ "id": "NotAValidPetId", // Invalid: should be integer "name": "dogs", }, "photoUrls": []string{"https://example.com/photo.jpg"}, }, } responseBody, _ := json.Marshal(pets) w.Write(responseBody) } handler(recorder, request) // Validate the response valid, validationErrs := docValidator.ValidateHttpResponse(request, recorder.Result()) if !valid { for _, e := range validationErrs { fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) if len(e.SchemaValidationErrors) > 0 { for _, schemaErr := range e.SchemaValidationErrors { fmt.Printf("Schema Error: %s at line %d, col %d\n", schemaErr.Reason, schemaErr.Line, schemaErr.Column) } } } } } ``` -------------------------------- ### ValidateHttpResponse Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Validates an HTTP response against the OpenAPI specification by matching it to the corresponding operation. ```APIDOC ## ValidateHttpResponse ### Description Validates an HTTP response against the OpenAPI specification. The request is used to locate the correct operation, and the response body and headers are validated against the expected schema. ### Parameters #### Request Body - **request** (http.Request) - Required - The original request used to identify the operation. - **response** (http.Response) - Required - The response object to validate. ``` -------------------------------- ### Validate Response Body with ResponseBodyValidator Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Uses the ResponseBodyValidator interface to validate HTTP response bodies against the OpenAPI specification. ```go package main import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" "github.com/pb33f/libopenapi-validator/helpers" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Get the response body validator respBodyValidator := docValidator.GetResponseBodyValidator() // Create request to identify the operation request, _ := http.NewRequest(http.MethodGet, "/pet/123", nil) // Create mock response recorder := httptest.NewRecorder() recorder.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) recorder.WriteHeader(http.StatusOK) pet := map[string]interface{}{ "id": 123, "name": "fluffy", "photoUrls": []string{"https://example.com/photo.jpg"}, } json.NewEncoder(recorder).Encode(pet) // Validate the response body valid, errs := respBodyValidator.ValidateResponseBody(request, recorder.Result()) if !valid { for _, e := range errs { fmt.Printf("Response body error: %s\n", e.Message) } } else { fmt.Println("Response body is valid!") } } ``` -------------------------------- ### Validate Request Body with RequestBodyValidator Source: https://context7.com/pb33f/libopenapi-validator/llms.txt Uses the RequestBodyValidator interface to validate HTTP request bodies against the OpenAPI specification. ```go package main import ( "fmt" "net/http" "os" "strings" "github.com/pb33f/libopenapi" validator "github.com/pb33f/libopenapi-validator" ) func main() { petstore, _ := os.ReadFile("openapi.yaml") document, _ := libopenapi.NewDocument(petstore) docValidator, _ := validator.NewValidator(document) // Get the request body validator reqBodyValidator := docValidator.GetRequestBodyValidator() // Create request with JSON body body := `{ "name": "fluffy", "photoUrls": ["https://example.com/photo.jpg"], "category": { "id": 1, "name": "dogs" } }` request, _ := http.NewRequest( http.MethodPost, "/pet", strings.NewReader(body), ) request.Header.Set("Content-Type", "application/json") // Validate the request body valid, errs := reqBodyValidator.ValidateRequestBody(request) if !valid { for _, e := range errs { fmt.Printf("Request body error: %s\n", e.Message) fmt.Printf("Reason: %s\n", e.Reason) } } else { fmt.Println("Request body is valid!") } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.