### Basic Operation Setup with Request and Response Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Sets up a basic HTTP GET operation, defines request and response structures using Go structs with tags, and registers the operation with the reflector. Includes defining path parameters and response content. ```go // Create operation context opCtx, err := reflector.NewOperationContext(http.MethodGet, "/users/{id}") if err != nil { log.Fatal(err) } // Define request structure type GetUserRequest struct { ID string `path:"id" example:"usr_123"` } // Define response structure type UserResponse struct { ID string `json:"id" example:"usr_123"` Name string `json:"name"` Email string `json:"email" format:"email"` CreatedAt time.Time `json:"created_at" format:"date-time"` } // Add request and response opCtx.AddReqStructure(new(GetUserRequest)) opCtx.AddRespStructure(new(UserResponse), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK cu.Description = "User retrieved successfully" }) // Register the operation err = reflector.AddOperation(opCtx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Complete OpenAPI Specification Example in Go Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md This Go code demonstrates how to initialize the openapi3.Reflector, configure API metadata, add security schemes, define operations (like creating and getting users) with request and response structures, and finally export the generated OpenAPI specification as YAML. It covers setting tags, summaries, IDs, security, and request/response bodies for API endpoints. ```go package main import ( "log" "net/http" "time" "github.com/swaggest/openapi-go/openapi3" "github.com/swaggest/openapi-go" ) func main() { reflector := openapi3.NewReflector() // Configure spec reflector.Spec.Info. WithTitle("User Management API"). WithVersion("1.0.0"). WithDescription("Manages user accounts and authentication") // Add security reflector.Spec.SetHTTPBearerTokenSecurity( "bearerAuth", "JWT", "Bearer token authentication", ) // Define operations type CreateUserReq struct { Email string `json:"email" required:"true" format:"email" Name string `json:"name" required:"true" } type UserResp struct { ID string `json:"id" Email string `json:"email" Name string `json:"name" CreatedAt time.Time `json:"created_at" } // Create user opCtx, err := reflector.NewOperationContext(http.MethodPost, "/users") if err != nil { log.Fatal(err) } opCtx.SetTags("users") opCtx.SetSummary("Create a new user") opCtx.SetID("createUser") opCtx.AddSecurity("bearerAuth") opCtx.AddReqStructure(new(CreateUserReq)) opCtx.AddRespStructure(new(UserResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusCreated }) if err := reflector.AddOperation(opCtx); err != nil { log.Fatal(err) } // Get user opCtx, err = reflector.NewOperationContext(http.MethodGet, "/users/{id}") if err != nil { log.Fatal(err) } opCtx.SetTags("users") opCtx.SetSummary("Get user by ID") opCtx.SetID("getUser") opCtx.AddSecurity("bearerAuth") type GetUserReq struct { ID string `path:"id" required:"true" } opCtx.AddReqStructure(new(GetUserReq)) opCtx.AddRespStructure(new(UserResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK }) if err := reflector.AddOperation(opCtx); err != nil { log.Fatal(err) } // Export yamlData, err := reflector.Spec.MarshalYAML() if err != nil { log.Fatal(err) } log.Println(string(yamlData)) } ``` -------------------------------- ### Path Pattern Parsing Examples Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md Provides examples of valid path pattern formats that the library automatically parses for parameter extraction. ```go // Valid formats: "/users/{id}" // Simple parameter "/users/{id:uuid}" // Gorilla mux regex pattern (converted to {id}) "/users/{userId}/posts/{postId}" // Multiple parameters ``` -------------------------------- ### Install OpenAPI-Go Library Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/README.md Import the necessary packages for OpenAPI 3.0 or 3.1. ```go import ( "github.com/swaggest/openapi-go/openapi3" // or "github.com/swaggest/openapi-go/openapi31" ) ``` -------------------------------- ### Handle file uploads Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/00-START-HERE.txt Implement file upload functionality using multipart form-data. Refer to practical-examples.md - Example 4 for a complete example. ```Go package main // FileUploadRequest defines the structure for file uploads. type FileUploadRequest struct { File []byte `form:"file"` // required, file upload Description string `form:"description"` // optional, string } ``` -------------------------------- ### SetupOperation Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Creates or updates an operation with setup functions. More flexible than AddOperation. ```APIDOC ## SetupOperation(method, path string, setup ...func(*Operation) error) ### Description Creates or updates an operation with setup functions. More flexible than AddOperation. ### Method Signature ```go func (s *Spec) SetupOperation( method, path string, setup ...func(*Operation) error, ) error ``` ### Parameters #### Path Parameters - **method** (string) - Required - HTTP method - **path** (string) - Required - URL path - **setup** (...func(*Operation) error) - Optional - Functions to configure the operation ### Returns - `error` — Non-nil if setup functions fail or validation fails ### Example ```go err := spec.SetupOperation("POST", "/users", func(op *openapi3.Operation) error { op.WithSummary("Create a new user") // ... more setup ... return nil }, ) ``` ``` -------------------------------- ### Work with pagination and complex filtering Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/00-START-HERE.txt Implement pagination and complex filtering for API requests. Refer to practical-examples.md - Example 3 for a detailed example. ```Go package main // ListItemsRequest defines parameters for listing items with pagination and filtering. type ListItemsRequest struct { Limit int `query:"limit"` // optional, default: 10, maximum: 100 Offset int `query:"offset"` // optional, default: 0 Status string `query:"status"` // optional, enum: active, inactive, pending Search string `query:"search"` // optional, string, for full-text search } ``` -------------------------------- ### Setup Operation in Spec Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Creates or updates an operation with setup functions. More flexible than AddOperation. Use when operations need dynamic configuration or updates. ```go func (s *Spec) SetupOperation( method, path string, setup ...func(*Operation) error, ) error err := spec.SetupOperation("POST", "/users", func(op *openapi3.Operation) error { op.WithSummary("Create a new user") // ... more setup ... return nil }, ) ``` -------------------------------- ### Set Example Value for Schema Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Use WithExample to provide a sample value that conforms to the schema. This aids in understanding and testing. ```go schema.WithExample(map[string]interface{}{ "id": 123, "name": "John Doe", }) ``` -------------------------------- ### Set up a reflector and generate specs Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/00-START-HERE.txt Use this to initialize the reflector and begin generating OpenAPI specifications. Refer to configuration-and-usage.md for detailed setup. ```Go package main import ( "context" "log" "github.com/swaggest/openapi-go/openapi3" ) func main() { ctx := context.Background() // Initialize OpenAPI 3.0.x reflector reflector := openapi3.NewReflector() // Setup spec metadata info := openapi3.Info{ Title: "My API", Version: "1.0.0", } reflector.Spec.Info.Set(info) // Build operations, configure servers, security, etc. // ... // Generate OpenAPI JSON sspec, err := reflector.Spec.MarshalJSON() if err != nil { log.Fatal(err) } // Output or save the spec // fmt.Println(string(sspec)) } ``` -------------------------------- ### Force Request Body for GET/HEAD Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Example of a request struct implementing 'ForceRequestBody' to allow a body for GET requests. This is generally not recommended and used for backward compatibility. ```go type GetWithBodyRequest struct { Filter string `json:"filter"` } // This tells the reflector to allow a body for GET requests func (GetWithBodyRequest) ForceRequestBody() {} ``` -------------------------------- ### Configure ContentUnit with Options Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Example demonstrating how to use 'ContentOption' functions like 'WithHTTPStatus' and 'WithContentType' to configure a 'ContentUnit' when adding a response structure. ```go opCtx.AddRespStructure(new(User), openapi.WithHTTPStatus(http.StatusOK), openapi.WithContentType("application/json"), ) ``` -------------------------------- ### Setting Up a Complete API Specification Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/README.md Demonstrates how to initialize a reflector, configure API metadata, security schemes, servers, and define operations with request and response structures. This is a comprehensive example for bootstrapping an OpenAPI specification. ```go reflector := openapi3.NewReflector() // Metadata reflector.Spec.Info. WithTitle("My API"). WithVersion("1.0.0"). WithDescription("Production API") // Security reflector.Spec.SetHTTPBearerTokenSecurity("bearerAuth", "JWT", "JWT token") // Servers reflector.Spec.WithServers( openapi3.Server{URL: "https://api.example.com"}, openapi3.Server{URL: "https://staging.example.com"}, ) // Operations opCtx, _ := reflector.NewOperationContext("POST", "/users") opCtx.AddSecurity("bearerAuth") opCtx.SetTags("users") opCtx.SetSummary("Create user") opCtx.AddReqStructure(new(CreateUserReq)) opCtx.AddRespStructure(new(UserResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusCreated }) reflector.AddOperation(opCtx) // Export yaml, _ := reflector.Spec.MarshalYAML() ``` -------------------------------- ### Validation Before Operation Example Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md Illustrates validating path parameters against struct tags before creating an operation context. ```go // Validate path parameters exist requiredParams := extractPathParams(pathPattern) providedParams := getStructTags(request, "path") missingParams := setDifference(requiredParams, providedParams) if len(missingParams) > 0 { return fmt.Errorf("missing path parameters: %v", missingParams) } // Then proceed with operation creation opCtx, _ := reflector.NewOperationContext(method, pathPattern) opCtx.AddReqStructure(request) ``` -------------------------------- ### Get API Version Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Retrieves the API version string. ```go spec.Version() ``` -------------------------------- ### Get API Description Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Retrieves the API description. Returns an empty string if not set. ```go spec.Description() ``` -------------------------------- ### Get HTTP Method of Operation Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Retrieves the HTTP method (e.g., 'get', 'post') for the current operation context. ```go opCtx, _ := reflector.NewOperationContext("POST", "/users") fmt.Println(opCtx.Method()) // Output: "post" ``` -------------------------------- ### User Management API Setup Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/practical-examples.md Sets up API operations for user registration, login, and profile management. It defines request and response structures with validation rules and OpenAPI schema annotations. ```go package main import ( "net/http" "time" "github.com/swaggest/openapi-go/openapi3" "github.com/swaggest/openapi-go" ) func setupUserAPI(reflector *openapi3.Reflector) error { // Types type User struct { ID string `json:"id" Email string `json:"email" format:"email" Username string `json:"username" pattern:"^[a-zA-Z0-9_]{3,32}$" FullName string `json:"full_name" Role string `json:"role" enum:"user,admin,moderator" Verified bool `json:"verified" CreatedAt time.Time `json:"created_at" format:"date-time" UpdatedAt time.Time `json:"updated_at" format:"date-time" } type RegisterReq struct { Email string `json:"email" required:"true" format:"email" Username string `json:"username" required:"true" pattern:"^[a-zA-Z0-9_]{3,32}$" Password string `json:"password" required:"true" minLength:"8" maxLength:"128" FullName string `json:"full_name" required:"true" minLength:"1" maxLength:"255" } type LoginReq struct { Email string `json:"email" required:"true" format:"email" Password string `json:"password" required:"true" } type TokenResp struct { AccessToken string `json:"access_token" RefreshToken string `json:"refresh_token" ExpiresIn int `json:"expires_in" } type ErrorResp struct { Code string `json:"code" Message string `json:"message" } // POST /auth/register opCtx, _ := reflector.NewOperationContext(http.MethodPost, "/auth/register") opCtx.SetTags("auth") opCtx.SetSummary("Register new user") opCtx.SetID("register") opCtx.AddReqStructure(new(RegisterReq)) opCtx.AddRespStructure(new(User), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusCreated }) opCtx.AddRespStructure(new(ErrorResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusConflict }) if err := reflector.AddOperation(opCtx); err != nil { return err } // POST /auth/login opCtx, _ = reflector.NewOperationContext(http.MethodPost, "/auth/login") opCtx.SetTags("auth") opCtx.SetSummary("Login user") opCtx.SetID("login") opCtx.AddReqStructure(new(LoginReq)) opCtx.AddRespStructure(new(TokenResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK }) if err := reflector.AddOperation(opCtx); err != nil { return err } // GET /users/me opCtx, _ = reflector.NewOperationContext(http.MethodGet, "/users/me") opCtx.SetTags("users") opCtx.SetSummary("Get current user") opCtx.SetID("getCurrentUser") opCtx.AddSecurity("jwtAuth") type GetMeReq struct { Authorization string `header:"Authorization" required:"true" } opCtx.AddReqStructure(new(GetMeReq)) opCtx.AddRespStructure(new(User), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK }) if err := reflector.AddOperation(opCtx); err != nil { return err } // GET /users/{id} opCtx, _ = reflector.NewOperationContext(http.MethodGet, "/users/{id}") opCtx.SetTags("users") opCtx.SetSummary("Get user by ID") opCtx.SetID("getUser") type GetUserReq struct { ID string `path:"id" required:"true" } opCtx.AddReqStructure(new(GetUserReq)) opCtx.AddRespStructure(new(User), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK }) opCtx.AddRespStructure(new(ErrorResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusNotFound }) if err := reflector.AddOperation(opCtx); err != nil { return err } // PATCH /users/{id} opCtx, _ = reflector.NewOperationContext(http.MethodPatch, "/users/{id}") opCtx.SetTags("users") opCtx.SetSummary("Update user") opCtx.SetID("updateUser") opCtx.AddSecurity("jwtAuth") type UpdateUserReq struct { ID string `path:"id" required:"true" Email string `json:"email" format:"email" FullName string `json:"full_name" Bio string `json:"bio" maxLength:"500" } opCtx.AddReqStructure(new(UpdateUserReq)) opCtx.AddRespStructure(new(User), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK }) if err := reflector.AddOperation(opCtx); err != nil { return err } return nil } ``` -------------------------------- ### Use JSONSchemaCallback in Schema Walking Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Example of defining and using a `JSONSchemaCallback` with `WalkRequestJSONSchemas` to print parameter details. ```go callback := func(in openapi.In, paramName string, schema *jsonschema.SchemaOrBool, required bool) error { fmt.Printf("Parameter: %s (in %s), required: %v\n", paramName, in, required) return nil } err := reflector.WalkRequestJSONSchemas("get", cu, callback, nil) ``` -------------------------------- ### Implement ContentUnitPreparer Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Example of a custom request struct implementing the 'ContentUnitPreparer' interface to define its content type and description. ```go type CustomRequest struct { Data string } func (r CustomRequest) SetupContentUnit(cu *openapi.ContentUnit) { cu.ContentType = "application/json" cu.Description = "Custom request format" } ``` -------------------------------- ### MarshalJSON Prevention Example Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md Shows how to correctly initialize an OpenAPI Spec to prevent MarshalJSON errors by including required fields. ```go spec := &openapi3.Spec{ Openapi: "3.0.3", Info: openapi3.Info{ Title: "API", Version: "1.0.0", }, Paths: openapi3.Paths{}, } jSONData, _ := spec.MarshalJSON() ``` -------------------------------- ### WithProperties Builder Method Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Example of using the WithProperties builder method to set all schema properties at once. This method takes a map of property names to SchemaOrRef objects. ```go schema.WithProperties(map[string]openapi3.SchemaOrRef{ "id": {Schema: &openapi3.Schema{Type: "integer"}}, "name": {Schema: &openapi3.Schema{Type: "string"}}, }) ``` -------------------------------- ### Initialize OpenAPI Reflector Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/INDEX.md Create a new reflector instance to start generating OpenAPI specifications. The generated spec is available via `reflector.Spec`. ```go reflector := openapi3.NewReflector() // reflector.Spec is the generated OpenAPI document ``` -------------------------------- ### Get Operation Summary Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Returns the operation summary. This provides read-only access to the short description of the operation. ```go func (oc OperationInfoReader) Summary() string ``` -------------------------------- ### Create Schema with References Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Store a schema in the components section and reference it from another schema. Use `openapi3.NewReflector().Spec` to get the spec, `ComponentsEns().SchemasEns().WithMapOfSchemaOrRefValuesItem` to store, and `SchemaReference` to reference. ```go spec := openapi3.NewReflector().Spec // Store the user schema in components spec.ComponentsEns().SchemasEns().WithMapOfSchemaOrRefValuesItem("User", openapi3.SchemaOrRef{ Schema: userSchema, }) // Reference it in another schema ordersSchema := &openapi3.Schema{} ordersSchema.WithType("array"). WithItems(openapi3.SchemaOrRef{ SchemaReference: &openapi3.SchemaReference{ Ref: "#/components/schemas/User", }, }) ``` -------------------------------- ### Spec Methods: Description and SetDescription Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Provides methods to get and set the description of the API specification, which corresponds to the Info.Description field. ```go func (s *Spec) Description() string func (s *Spec) SetDescription(d string) ``` -------------------------------- ### Spec Methods: Version and SetVersion Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Provides methods to get and set the version of the API specification, which corresponds to the Info.Version field. ```go func (s *Spec) Version() string func (s *Spec) SetVersion(v string) ``` -------------------------------- ### WithPropertiesItem Builder Method Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Example of using the WithPropertiesItem builder method to add a single property to the schema. This is useful for defining properties incrementally. ```go schema.WithPropertiesItem("email", openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: "string", Format: "email", }, }) ``` -------------------------------- ### WithType Builder Method Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Example of using the WithType builder method to set the schema type and WithTitle to set its title. This is part of the fluent configuration pattern. ```go schema := &openapi3.Schema{} schema.WithType("object"). WithTitle("User") ``` -------------------------------- ### Get OpenAPI Path Pattern Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Retrieves the normalized OpenAPI path pattern, including parameter placeholders like /users/{id}. ```go opCtx, _ := reflector.NewOperationContext("GET", "/items/{id}") fmt.Println(opCtx.PathPattern()) // Output: "/items/{id}" ``` -------------------------------- ### Handle JSON Schema Validation Errors Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md The JSON schema reflector may fail to process Go structures, leading to errors like 'setup request' or 'setup response'. This can be due to circular references, unsupported types, or invalid struct tags. This example shows a circular reference and its prevention. ```go type Node struct { Value string Child *Node // Circular reference } opCtx.AddReqStructure(new(Node)) reflector.AddOperation(opCtx) // Potential error depending on schema setup ``` ```go // Use references for circular types type Node struct { Value string ChildRef *string `json:"child_ref"` // Reference ID instead } ``` -------------------------------- ### Setting Up a Complete API Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/README.md Demonstrates how to initialize a reflector, set API metadata (title, version, description), configure security schemes, define servers, and add operations with request and response structures. ```APIDOC ## Setting Up a Complete API ### Description This example shows the process of setting up a complete API specification using the OpenAPI Go library. It covers initializing the reflector, defining API metadata, configuring security, adding server information, and defining individual API operations including their request and response structures. ### Method ```go reflector := openapi3.NewReflector() // Metadata reflector.Spec.Info. WithTitle("My API"). WithVersion("1.0.0"). WithDescription("Production API") // Security reflector.Spec.SetHTTPBearerTokenSecurity("bearerAuth", "JWT", "JWT token") // Servers reflector.Spec.WithServers( openapi3.Server{URL: "https://api.example.com"}, openapi3.Server{URL: "https://staging.example.com"}, ) // Operations opCtx, _ := reflector.NewOperationContext("POST", "/users") opCtx.AddSecurity("bearerAuth") opCtx.SetTags("users") opCtx.SetSummary("Create user") opCtx.AddReqStructure(new(CreateUserReq)) opCtx.AddRespStructure(new(UserResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusCreated }) reflector.AddOperation(opCtx) // Export yaml, _ := reflector.Spec.MarshalYAML() ``` ### Request Example ```json { "example": "request body" } ``` ### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Debug validation errors Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/00-START-HERE.txt Guide to debugging validation errors, including operation creation, path parameter, JSON schema, and serialization errors. Refer to errors-and-validation.md. ```Go package main import ( "context" "log" "github.com/swaggest/openapi-go/errors" "github.com/swaggest/openapi-go/openapi3" ) func main() { ctx := context.Background() reflector := openapi3.NewReflector() // Example: Handling operation creation errors _, err := reflector.NewOperation(ctx, "invalid-operation-id") if err != nil { if opErr, ok := err.(*errors.OperationError); ok { log.Printf("Operation creation error: %s\n", opErr.Error()) } } // Example: Handling path parameter validation errors // ... (requires defining an operation with path parameters) // Example: Handling JSON schema errors // ... (requires defining schemas and attempting to validate data) // Example: Handling serialization errors // ... (requires attempting to serialize invalid data) } ``` -------------------------------- ### JSON Tags Reference Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Demonstrates various JSON tags for defining field properties like `required`, `format`, `minimum`, `maximum`, `minLength`, `maxLength`, `minItems`, `maxItems`, `enum`, `example`, `readOnly`, and `hidden`. ```go type Example struct { ID int `json:"id"` // Basic JSON field Name string `json:"name" required:"true"` // Required field Email string `json:"email" format:"email"` // With format Age int `json:"age" minimum:"0" maximum:"150"` // Numeric constraints Bio string `json:"bio" minLength:"10" maxLength:"500"` // String constraints Tags []string `json:"tags" minItems:"1" maxItems:"10"` // Array constraints Status string `json:"status" enum:"active,inactive"` // Enum values Example string `json:"example" example:"Hello World"` // Example value ReadOnly bool `json:"read_only" readOnly:"true"` // Read-only field Hidden bool `json:"hidden" hidden:"true"` // Hidden from docs } ``` -------------------------------- ### Get API Title Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Retrieves the API title from the Info object. Used to get the service/API title. ```go title := spec.Title() fmt.Println("API Name:", title) ``` -------------------------------- ### Enforce Request Body on GET Method Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Defines a struct for a GET request that requires a request body and implements the ForceRequestBody marker interface. ```go type GetWithBody struct { Filter string `json:"filter"` } // Implement marker interface to force body on GET func (GetWithBody) ForceRequestBody() {} opCtx, _ := reflector.NewOperationContext(http.MethodGet, "/search") opCtx.AddReqStructure(new(GetWithBody)) ``` -------------------------------- ### Configure security (JWT, API Key, Basic Auth) Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/00-START-HERE.txt Set up security schemes like JWT, API Key, or Basic Auth for your API. Refer to configuration-and-usage.md for detailed security configuration. ```Go package main import ( "context" "log" "github.com/swaggest/openapi-go/openapi3" ) func main() { ctx := context.Background() reflector := openapi3.NewReflector() // Configure API Key security scheme apiKeyScheme := openapi3.APIKeySecurityScheme{Name: "X-API-Key", In: "header"} apiKeyRequirement := openapi3.SecurityRequirement(map[string]interface{}{"apiKey": {}}) reflector.AddSecurityRequirement(apiKeyRequirement) reflector.AddSecurityScheme("apiKey", apiKeyScheme) // Configure JWT security scheme jwtScheme := openapi3.HTTPBearerScheme{} jwtRequirement := openapi3.SecurityRequirement(map[string]interface{}{"bearerAuth": {}}) reflector.AddSecurityRequirement(jwtRequirement) reflector.AddSecurityScheme("bearerAuth", jwtScheme) // ... other configurations } ``` -------------------------------- ### Create Product Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/practical-examples.md Creates a new product listing. Requires admin privileges. Returns the created product or a validation error. ```APIDOC ## POST /products ### Description Creates a new product listing. Requires admin privileges. ### Method POST ### Endpoint /products ### Parameters #### Request Body - **name** (string) - Required - Name of the product, between 1 and 255 characters. - **description** (string) - Optional - Description of the product, up to 5000 characters. - **price** (object) - Required - The price of the product. - **amount** (number) - Required - The price amount, must be non-negative. - **currency** (string) - Optional - The currency of the price (e.g., USD, EUR, GBP), defaults to USD. - **category** (string) - Required - The category of the product. - **image_url** (string) - Optional - URL of the product image, must be a valid URI. ### Request Example { "example": "{\n \"name\": \"Laptop Pro\",\n \"description\": \"High-performance laptop for professionals.\",\n \"price\": {\n \"amount\": 1200.00,\n \"currency\": \"USD\"\n },\n \"category\": \"Electronics\",\n \"image_url\": \"https://api.store.com/images/laptop-pro.jpg\"\n}" } ### Response #### Success Response (201 Created) - **id** (string) - Unique identifier for the product. - **name** (string) - Name of the product. - **description** (string) - Description of the product. - **price** (object) - The price of the product. - **amount** (number) - The price amount. - **currency** (string) - The currency of the price. - **stock** (integer) - Current stock level. - **category** (string) - The category of the product. - **image_url** (string) - URL of the product image. - **created_at** (string) - Timestamp when the product was created (ISO 8601 format). - **updated_at** (string) - Timestamp when the product was last updated (ISO 8601 format). #### Response Example { "example": "{\n \"id\": \"prod_12345\",\n \"name\": \"Laptop Pro\",\n \"description\": \"High-performance laptop for professionals.\",\n \"price\": {\n \"amount\": 1200.00,\n \"currency\": \"USD\"\n },\n \"stock\": 50,\n \"category\": \"Electronics\",\n \"image_url\": \"https://api.store.com/images/laptop-pro.jpg\",\n \"created_at\": \"2023-10-27T10:00:00Z\",\n \"updated_at\": \"2023-10-27T10:00:00Z\"\n}" } #### Error Response (400 Bad Request) - **code** (string) - Error code (e.g., \"VALIDATION_ERROR\"). - **message** (string) - Error message describing the validation failure. - **details** (object) - Optional - Additional details about the validation errors. ``` -------------------------------- ### RequestBodyEnforcer Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Marker interface indicating that a GET or HEAD request should have a request body. ```APIDOC ## RequestBodyEnforcer ### Description Marker interface indicating that a GET or HEAD request should have a request body. Implementing this interface on request structures overrides the normal behavior (GET/HEAD don't have bodies). Should be implemented with an empty function body. **Note:** Forcing request body is not recommended and should only be used for backwards compatibility. ### Example ```go type GetWithBodyRequest struct { Filter string `json:"filter"` } // This tells the reflector to allow a body for GET requests func (GetWithBodyRequest) ForceRequestBody() {} ``` ``` -------------------------------- ### Path Tags Reference Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Shows how to define path parameters using the `path` tag. Path parameters are always considered required. ```go type PathParams struct { ID string `path:"id" required:"true"` // Path parameter (always required) Type string `path:"type"` } ``` -------------------------------- ### Get Product List Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/practical-examples.md Retrieves a list of all products. This operation is part of the E-Commerce API. ```APIDOC ## GET /products ### Description Retrieves a list of all products. ### Method GET ### Endpoint /products ### Response #### Success Response (200) - **Products** (array) - Product list retrieved successfully ``` -------------------------------- ### Get Product by ID Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/practical-examples.md Retrieves a specific product by its ID. This operation is part of the E-Commerce API. ```APIDOC ## GET /products/{id} ### Description Get product by ID. ### Method GET ### Endpoint /products/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the product to retrieve. ### Response #### Success Response (200) - **Product** (object) - Product details retrieved successfully. #### Error Response (404) - **ErrorResponse** (object) - Product not found. ``` -------------------------------- ### Header Tags Reference Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Demonstrates header parameter tags, including mapping to header names (`header`), setting `required` status, and providing `default` values. ```go type HeaderParams struct { Auth string `header:"Authorization" required:"true"` Trace string `header:"X-Trace-ID"` Accept string `header:"Accept" default:"application/json"` } ``` -------------------------------- ### GET /things/{id} Source: https://github.com/swaggest/openapi-go/blob/master/README.md Retrieves a specific thing by its ID. It returns the thing object if found. ```APIDOC ## GET /things/{id} ### Description Retrieves a specific thing by its ID. It returns the thing object if found. ### Method GET ### Endpoint /things/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the thing. #### Query Parameters - **locale** (string) - Optional - The locale for the request, must follow the pattern `^[a-z]{2}-[A-Z]{2}$`. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the thing. - **Amount** (uint) - The amount associated with the thing. - **Items** (array) - A list of items associated with the thing. - **Count** (uint) - The count of the item. - **Name** (string) - The name of the item. - **updated_at** (time.Time) - The timestamp when the thing was last updated. #### Response Example (200) ```json { "id": "XXX-XXXXX", "amount": 100, "items": [ { "count": 5, "name": "Item 1" } ], "updated_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Initialize Operation Context and Add Request Structure Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-reflector.md Creates an operation context for a given HTTP method and path, then adds a request structure to it. Handles path parameters and validates HTTP methods. ```Go opCtx, err := reflector.NewOperationContext(http.MethodPost, "/users/{id}") if err != nil { log.Fatal(err) } type CreateUserReq struct { Name string `json:"name"` } opCtx.AddReqStructure(new(CreateUserReq)) ``` -------------------------------- ### GET /users/me Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/practical-examples.md Retrieves the profile information of the currently authenticated user. Requires a JWT in the Authorization header. ```APIDOC ## GET /users/me ### Description Retrieves the profile information of the currently authenticated user. Requires a JWT in the Authorization header. ### Method GET ### Endpoint /users/me ### Parameters #### Header Parameters - **Authorization** (string) - Required - JWT token for authentication. ### Response #### Success Response (200 OK) - **id** (string) - Unique identifier for the user. - **email** (string) - Email address of the user. - **username** (string) - Username of the user. - **full_name** (string) - Full name of the user. - **role** (string) - Role of the user (user, admin, moderator). - **verified** (boolean) - Indicates if the user account is verified. - **created_at** (string) - Timestamp when the user was created. - **updated_at** (string) - Timestamp when the user was last updated. ``` -------------------------------- ### Get Operation ID Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Returns the operation ID. This provides read-only access to the unique identifier for the operation. ```go func (oc OperationInfoReader) ID() string ``` -------------------------------- ### Basic OpenAPI Specification Generation Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/README.md Demonstrates creating an OpenAPI specification, defining request and response structures, and adding an operation. The generated specification is then marshaled to YAML. ```go package main import ( "net/http" "log" "github.com/swaggest/openapi-go/openapi3" "github.com/swaggest/openapi-go" ) func main() { reflector := openapi3.NewReflector() reflector.Spec.Info.WithTitle("My API").WithVersion("1.0.0") type CreateUserReq struct { Name string `json:"name"` Email string `json:"email" format:"email"` } type UserResp struct { ID string `json:"id"` Name string `json:"name"` Email string `json:"email"` } opCtx, _ := reflector.NewOperationContext(http.MethodPost, "/users") opCtx.AddReqStructure(new(CreateUserReq)) opCtx.AddRespStructure(new(UserResp), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusCreated }) reflector.AddOperation(opCtx) yaml, _ := reflector.Spec.MarshalYAML() log.Println(string(yaml)) } ``` -------------------------------- ### Handle different parameter locations Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/00-START-HERE.txt Configure request parameters like path, query, and header using field tags. Refer to the Field Tags Reference for details. ```Go package main // GetUserRequest defines parameters for retrieving a user. type GetUserRequest struct { UserID int64 `path:"userId"` // required, int64 Expand string `query:"expand"` // optional, string APIKey string `header:"X-API-Key"` // required, string } ``` -------------------------------- ### Get Operation Description Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Returns the operation description. This provides read-only access to the detailed description of the operation. ```go func (oc OperationInfoReader) Description() string ``` -------------------------------- ### Configure API Metadata with Builder Methods Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/INDEX.md Utilize fluent builder methods to set API information such as title, version, and description. ```go spec.Info. WithTitle("API"). WithVersion("1.0.0"). WithDescription("My API") ``` -------------------------------- ### OpenAPI-Go Package Structure Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/README.md Illustrates the directory structure of the openapi-go project, highlighting the main packages for abstract interfaces, OpenAPI 3.0, OpenAPI 3.1, and internal components. ```go github.com/swaggest/openapi-go/ ├── openapi/ (Abstract interfaces and types) ├── openapi3/ (OpenAPI 3.0.x implementation) ├── openapi31/ (OpenAPI 3.1.0 implementation) ├── internal/ (Shared internals) └── ... ``` -------------------------------- ### Get Operation Tags Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Returns the operation tags. This provides read-only access to the tags set for the operation. ```go func (oc OperationInfoReader) Tags() []string ``` -------------------------------- ### Implement ForceJSONRequestBody for FormStructAsJSON Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Example of implementing `ForceJSONRequestBody` to ensure a struct with `formData` tags is sent as JSON. ```go type FormStructAsJSON struct { Username string `formData:"user" Password string `formData:"pass" } // Force JSON encoding instead of form-urlencoded func (FormStructAsJSON) ForceJSONRequestBody() {} ``` -------------------------------- ### Create Simple Object Schema Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Define a basic object schema with properties like ID, email, and name. Use `WithType`, `WithTitle`, `WithDescription`, `WithRequired`, and `WithPropertiesItem` to configure the schema. ```go userSchema := &openapi3.Schema{} userSchema.WithType("object"). WithTitle("User"). WithDescription("A registered user"). WithRequired("id", "email"). WithPropertiesItem("id", openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: "integer", Format: "int64", }, }). WithPropertiesItem("email", openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: "string", Format: "email", }, }). WithPropertiesItem("name", openapi3.SchemaOrRef{ Schema: &openapi3.Schema{ Type: "string", }, }) ``` -------------------------------- ### Wrap Parameter in ParameterOrRef Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Example of wrapping a Parameter struct into a ParameterOrRef union type using the ToParameterOrRef method. ```go param := Parameter{ Name: "id", In: "path", Required: true, } paramOrRef := param.ToParameterOrRef() ``` -------------------------------- ### UnmarshalJSON Error Example Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md Illustrates an error when UnmarshalJSON is used with invalid JSON or YAML structure for an OpenAPI Spec. ```go var spec openapi3.Spec err := spec.UnmarshalJSON([]byte(`{"openapi": "invalid"}`)) // err: "required key missing: info" ``` -------------------------------- ### MarshalJSON Error Example Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md Demonstrates an error scenario when MarshalJSON is called on an OpenAPI Spec with missing required fields. ```go spec := &openapi3.Spec{} // Missing required fields jsonData, err := spec.MarshalJSON() // err: "required key missing: openapi" ``` -------------------------------- ### Query Tags Reference Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Illustrates query parameter tags, including mapping to parameter names (`query`), setting `default` values, marking as `required`, and applying `pattern` validation. ```go type QueryParams struct { Search string `query:"q"` // Query parameter "q" Page int `query:"page" default:"1"` // With default PageSize int `query:"page_size" required:"true"` // Required SortBy string `query:"sort_by" pattern:"^[a-z_]+$"` // With pattern } ``` -------------------------------- ### Create Spec using Reflector Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Creates an OpenAPI 3.0.x specification document using the Reflector utility. This is the typical way to initialize a Spec. ```go reflector := openapi3.NewReflector() spec := reflector.Spec // Direct access to spec ``` -------------------------------- ### Path Parameter Tagging Solution Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/errors-and-validation.md Shows correct usage of the `path` tag for request struct fields to ensure path parameters are recognized. ```go // Check 1: Use `path` tag type Request struct { ID string `path:"id"` // ✓ Correct ID string `query:"id"` // ✗ Wrong location } // Check 2: Match placeholder name exactly opCtx, _ := reflector.NewOperationContext("GET", "/users/{id}") type Request struct { ID string `path:"id"` // ✓ Matches placeholder ID string `path:"userId"` // ✗ Doesn't match } ``` -------------------------------- ### Spec Methods: Title and SetTitle Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Provides methods to get and set the title of the API specification, which corresponds to the Info.Title field. ```go func (s *Spec) Title() string func (s *Spec) SetTitle(t string) ``` -------------------------------- ### Set API Description Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Sets the API description. The 'd' parameter is the API description string. ```go spec.SetDescription("Manages user accounts and authentication") ``` -------------------------------- ### Get Response Content Units Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-operation.md Retrieves all added response content units, supporting multiple response statuses or content types. ```go opCtx, _ := reflector.NewOperationContext("GET", "/users/{id}") opCtx.AddRespStructure(new(User), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusOK }) opCtx.AddRespStructure(new(ErrorResponse), func(cu *openapi.ContentUnit) { cu.HTTPStatus = http.StatusNotFound }) resps := opCtx.Response() fmt.Println("Number of responses:", len(resps)) // Output: 2 ``` -------------------------------- ### Configure Info Object Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-spec.md Builder methods for configuring the Info object, including title, version, description, and contact details. Use to define metadata for your API. ```go type Info struct { Title string // Required Description *string TermsOfService *string Contact *Contact License *License Version string // Required MapOfAnything map[string]interface{} // Extension fields (x-*) } info := Info{} info.WithTitle("Pet Store API"). WithVersion("1.0.0"). WithDescription("API for managing pets"). WithContact(Contact{ Name: "API Support", URL: "https://example.com/support", }) spec.WithInfo(info) ``` -------------------------------- ### Set Schema Description Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/api-reference-schema.md Use WithDescription to add a human-readable description to a schema, explaining its purpose or content. ```go schema.WithDescription("User information schema") ``` -------------------------------- ### Access and Modify Operation via OperationExposer Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/types.md Example of type asserting an `OperationContext` to `openapi3.OperationExposer` to access and modify the underlying `Operation` structure. ```go opCtx, _ := reflector.NewOperationContext("POST", "/users") // Type assert to access Operation if exposer, ok := opCtx.(openapi3.OperationExposer); ok { op := exposer.Operation() op.WithDeprecated(true) op.WithDescription("Deprecated: use v2 instead") } ``` -------------------------------- ### Define List Request with Query Parameters Source: https://github.com/swaggest/openapi-go/blob/master/_autodocs/configuration-and-usage.md Defines a request structure for listing users, specifying query parameters for search, pagination (page, limit), and sorting. Includes validation constraints like minimum and maximum values, and patterns. ```go type ListUsersRequest struct { Search string `query:"q" description:"Search term"` Page int `query:"page" minimum:"1" default:"1"` Limit int `query:"limit" minimum:"1" maximum:"100" default:"20"` Sort string `query:"sort" pattern:"^(name|email|created)$"` } opCtx, _ := reflector.NewOperationContext(http.MethodGet, "/users") opCtx.AddReqStructure(new(ListUsersRequest)) ```