### Install oapi-codegen Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/README.md Install the oapi-codegen tool using go get. Go 1.25 or later is required. ```bash go get -tool github.com/oapi-codegen/oapi-codegen-exp/cmd/oapi-codegen@latest ``` -------------------------------- ### oapi-codegen V3 Configuration File Example Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt A comprehensive YAML configuration file for `oapi-codegen` V3, demonstrating options for package name, output file, generation settings (server, client, webhooks, callbacks), model and runtime package imports, and output options. ```yaml # config.yaml — fully annotated example package: petstore # Go package name for generated code output: petstore.gen.go # output file (default: .gen.go) generation: # Server framework: "std-http" | "chi" | "echo" | "echo/v4" | "gin" | "gorilla" | "fiber" | "iris" server: chi # HTTP client (returns *http.Response per operation) client: true # SimpleClient: typed-response wrapper around the base client simple-client: true # Webhook support (OpenAPI 3.1 webhooks section) webhook-initiator: true # generate code to SEND webhook requests webhook-receiver: true # generate handler code to RECEIVE webhooks (requires server) # Callback support (OpenAPI 3.1 callbacks on operations) callback-initiator: true callback-receiver: true # requires server # Import model types from another package instead of generating them models-package: path: github.com/org/project/models alias: models # optional; defaults to last segment of path # Use a shared runtime package instead of inlining helpers runtime-package: path: github.com/org/project/runtime # Disable the oneOf+const enum detection (default: false = detection enabled) skip-enum-via-oneof: false output-options: include-tags: [public] # only include operations with these tags exclude-tags: [internal] include-operation-ids: [listPets, createPet] exclude-operation-ids: [deprecatedEndpoint] exclude-schemas: [InternalConfig] prune-unreferenced-schemas: true always-prefix-enum-values: false # Override OpenAPI primitive → Go type mappings type-mapping: string: formats: money: type: decimal.Decimal import: github.com/shopspring/decimal # Control how OpenAPI names become Go identifiers name-mangling: numeric-prefix: "N" initialisms: [API, HTTP, ID, URL, UUID] # Direct name overrides name-substitutions: type-names: foo: MyCustomFoo property-names: bar: MyCustomBar # Resolve external $ref targets to Go packages import-mapping: ../common/api.yaml: github.com/org/project/common ../other/api.yaml: other github.com/org/project/other # explicit alias ./local-types.yaml: "-" # current package ``` -------------------------------- ### Install oapi-codegen V3 as a Go Tool Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Add the oapi-codegen V3 tool to your Go module dependencies. Use `go:generate` to invoke the code generation process. ```bash # Add the tool to your module go get -tool github.com/oapi-codegen/oapi-codegen-exp/cmd/oapi-codegen@latest # Use go:generate to invoke it (place in any .go file) //go:generate go run github.com/oapi-codegen/oapi-codegen-exp/cmd/oapi-codegen -config config.yaml petstore.yaml ``` -------------------------------- ### Simple Client Generation Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Generate a `SimpleClient` wrapper that returns typed Go values instead of raw `*http.Response`. Operations with a single unambiguous success response type get a fully typed method. ```APIDOC ## Client generation — `SimpleClient` Set `simple-client: true` (requires `client: true`) to generate a `SimpleClient` wrapper with methods that return typed Go values rather than raw `*http.Response`. Operations with a single unambiguous success response type get a fully typed method. ```go // generation: // client: true // simple-client: true package main import ( "context" "fmt" "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded/client" petstore "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded" ) func main() { base, _ := client.NewClient("https://petstore.swagger.io/api") sc := client.NewSimpleClient(base) // FindPets returns ([]petstore.Pet, error) — no manual JSON decoding needed limit := int32(5) pets, err := sc.FindPets(context.Background(), &client.FindPetsParams{Limit: &limit}) if err != nil { // ClientHttpError[petstore.Error] carries StatusCode + typed Body if httpErr, ok := err.(*client.ClientHttpError[petstore.Error]); ok { fmt.Printf("API error %d: %s\n", httpErr.StatusCode, httpErr.Body.Message) return } panic(err) } for _, p := range pets { fmt.Printf("%s (%s)\n", p.Name, *p.Tag) } // AddPet returns (petstore.Pet, error) newPet, err := sc.AddPet(context.Background(), petstore.NewPet{Name: "Whiskers"}) if err != nil { panic(err) } fmt.Printf("Added: %s with ID %d\n", newPet.Name, newPet.ID) } ``` ``` -------------------------------- ### Generate Base Client with Request Editor Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Configure `client: true` in `client.config.yaml` to generate a `Client` struct. Use `NewClient` with an optional `RequestEditorFn` to customize requests, such as adding authentication headers. ```yaml // client.config.yaml: // generation: // client: true ``` ```go package main import ( "context" "encoding/json" "fmt" "net/http" "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded/client" petstore "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded" ) func main() { // Create client with optional editor (e.g., add auth header) c, err := client.NewClient("https://petstore.swagger.io/api", client.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error { req.Header.Set("Authorization", "Bearer my-token") return nil }), ) if err != nil { panic(err) } // List pets with optional tag filter and limit limit := int32(10) resp, err := c.FindPets(context.Background(), &client.FindPetsParams{ Limit: &limit, }) if err != nil { panic(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { panic(fmt.Sprintf("unexpected status %d", resp.StatusCode)) } var pets []petstore.Pet if err := json.NewDecoder(resp.Body).Decode(&pets); err != nil { panic(err) } for _, p := range pets { fmt.Printf("Pet #%d: %s\n", p.ID, p.Name) } // Create a new pet newPetResp, err := c.AddPet(context.Background(), petstore.NewPet{Name: "Fido", Tag: ptr("dog")}) if err != nil { panic(err) } defer newPetResp.Body.Close() var created petstore.Pet json.NewDecoder(newPetResp.Body).Decode(&created) fmt.Printf("Created pet #%d\n", created.ID) // Output: Created pet #1000 } func ptr[T any](v T) *T { return &v } ``` -------------------------------- ### Send Callbacks with CallbackInitiator Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Use the generated CallbackInitiator to send callback notifications. Ensure the server is configured with `callback-initiator: true`. ```go // SERVER: use generated CallbackInitiator to fire callbacks package main import ( "context" "log" "time" "github.com/google/uuid" treefarm "github.com/oapi-codegen/oapi-codegen-exp/examples/callback" ) func plantTree(callbackURL string, tree treefarm.TreeWithId) { // Simulate planting delay time.Sleep(2 * time.Second) initiator, _ := treefarm.NewCallbackInitiator() result := treefarm.TreePlantingResult{ TreeWithId: tree, Success: true, } resp, err := initiator.TreePlanted(context.Background(), callbackURL, result) if err != nil { log.Printf("callback failed: %v", err) return } defer resp.Body.Close() log.Printf("callback delivered, status=%d", resp.StatusCode) } // Implement server.ServerInterface.PlantTree: // func (s *TreeFarmServer) PlantTree(w http.ResponseWriter, r *http.Request) { // var req treefarm.TreePlantingRequest // json.NewDecoder(r.Body).Decode(&req) // tree := treefarm.TreeWithId{Tree: req.Tree, ID: uuid.New()} // go plantTree(req.CallbackUrl, tree) // fire and forget // w.WriteHeader(http.StatusAccepted) // json.NewEncoder(w).Encode(tree) // } _ = uuid.New ``` -------------------------------- ### Receive Webhooks with WebhookReceiverInterface Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Implement the generated WebhookReceiverInterface to handle incoming webhook events. Configure the server with `webhook-receiver: true`. ```go // CLIENT: receive webhooks (implement the generated WebhookReceiverInterface) package main import ( "encoding/json" "log" "net/http" doorbadge "github.com/oapi-codegen/oapi-codegen-exp/examples/webhook" ) type MyReceiver struct{} func (r *MyReceiver) EnterEvent(w http.ResponseWriter, req *http.Request) { var person doorbadge.Person json.NewDecoder(req.Body).Decode(&person) log.Printf("ENTER: %s", person.Name) w.WriteHeader(http.StatusOK) } func (r *MyReceiver) ExitEvent(w http.ResponseWriter, req *http.Request) { var person doorbadge.Person json.NewDecoder(req.Body).Decode(&person) log.Printf("EXIT: %s", person.Name) w.WriteHeader(http.StatusOK) } func main() { mux := http.NewServeMux() // Generated WebhookHandlerFromMux wires EnterEvent / ExitEvent doorbadge.WebhookHandlerFromMux(&MyReceiver{}, mux) log.Fatal(http.ListenAndServe(":9090", mux)) } ``` -------------------------------- ### Basic oapi-codegen Configuration Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md This is a basic configuration file for oapi-codegen, specifying the Go package name and the output file path for generated code. ```yaml package: myapi output: types.gen.go ``` -------------------------------- ### Generate SimpleClient for Typed Responses Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Enable `simple-client: true` (along with `client: true`) to generate a `SimpleClient` that returns typed Go values instead of raw `*http.Response`. This simplifies handling responses, especially for operations with a single success type. ```yaml // generation: // client: true // simple-client: true ``` ```go package main import ( "context" "fmt" "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded/client" petstore "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded" ) func main() { base, _ := client.NewClient("https://petstore.swagger.io/api") sc := client.NewSimpleClient(base) // FindPets returns ([]petstore.Pet, error) — no manual JSON decoding needed limit := int32(5) pets, err := sc.FindPets(context.Background(), &client.FindPetsParams{Limit: &limit}) if err != nil { // ClientHttpError[petstore.Error] carries StatusCode + typed Body if httpErr, ok := err.(*client.ClientHttpError[petstore.Error]); ok { fmt.Printf("API error %d: %s\n", httpErr.StatusCode, httpErr.Body.Message) return } panic(err) } for _, p := range pets { fmt.Printf("%s (%s)\n", p.Name, *p.Tag) } // AddPet returns (petstore.Pet, error) newPet, err := sc.AddPet(context.Background(), petstore.NewPet{Name: "Whiskers"}) if err != nil { panic(err) } fmt.Printf("Added: %s with ID %d\n", newPet.Name, newPet.ID) } ``` -------------------------------- ### Apply Defaults to OpenAPI Config in Go Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Demonstrates how to unmarshal a partial configuration from JSON and apply default values defined in the OpenAPI spec using the ApplyDefaults method. Ensure the Config struct is generated by oapi-codegen. ```go package main import ( "encoding/json" "fmt" "github.com/org/project/api" ) func main() { // Unmarshal a partial config from JSON var cfg api.Config json.Unmarshal([]byte(`{"timeout": 60}`), &cfg) // Before ApplyDefaults: retries and debug are zero-values fmt.Println(*cfg.Timeout) // 60 fmt.Println(cfg.Retries) // // Apply spec defaults to unset optional fields cfg.ApplyDefaults() fmt.Println(*cfg.Timeout) // 60 — already set, not overwritten fmt.Println(*cfg.Retries) // 3 — default applied fmt.Println(*cfg.Debug) // false — default applied } ``` -------------------------------- ### Programmatic Code Generation with codegen.Generate Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Use `codegen.Generate` to programmatically generate Go code from an OpenAPI specification. Configure generation options like server type, client generation, and package name. Ensure external references are handled appropriately, potentially by skipping resolution and using import mapping. ```go package main import ( "fmt" "os" "github.com/pb33f/libopenapi" "github.com/pb33f/libopenapi/datamodel" "github.com/oapi-codegen/oapi-codegen-exp/codegen" ) func main() { specData, err := os.ReadFile("petstore-expanded.yaml") if err != nil { panic(err) } // Skip external ref resolution (handle via import-mapping instead) docCfg := datamodel.NewDocumentConfiguration() docCfg.SkipExternalRefResolution = true doc, err := libopenapi.NewDocumentWithConfiguration(specData, docCfg) if err != nil { panic(err) } cfg := codegen.Configuration{ PackageName: "petstore", Output: "petstore.gen.go", Generation: codegen.GenerationOptions{ Server: codegen.ServerTypeChi, Client: true, SimpleClient: true, }, } code, err := codegen.Generate(doc, specData, cfg) if err != nil { panic(err) } if err := os.WriteFile(cfg.Output, []byte(code), 0644); err != nil { panic(err) } fmt.Println("Generated", cfg.Output) // Output: Generated petstore.gen.go } ``` -------------------------------- ### Base Client Generation Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Generate a `Client` struct with a method for each API operation. Each method takes a `context.Context`, typed parameters, and optional `RequestEditorFn` callbacks, returning `(*http.Response, error)`. ```APIDOC ## Client generation — base `Client` Set `client: true` to generate a `Client` struct with a method per operation. Each method accepts a `context.Context`, typed parameter structs, and optional `RequestEditorFn` callbacks; it returns `(*http.Response, error)`. ```go // client.config.yaml: // generation: // client: true package main import ( "context" "encoding/json" "fmt" "net/http" "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded/client" petstore "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded" ) func main() { // Create client with optional editor (e.g., add auth header) c, err := client.NewClient("https://petstore.swagger.io/api", client.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error { req.Header.Set("Authorization", "Bearer my-token") return nil }), ) if err != nil { panic(err) } // List pets with optional tag filter and limit limit := int32(10) resp, err := c.FindPets(context.Background(), &client.FindPetsParams{ Limit: &limit, }) if err != nil { panic(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { panic(fmt.Sprintf("unexpected status %d", resp.StatusCode)) } var pets []petstore.Pet if err := json.NewDecoder(resp.Body).Decode(&pets); err != nil { panic(err) } for _, p := range pets { fmt.Printf("Pet #%d: %s\n", p.ID, p.Name) } // Create a new pet newPetResp, err := c.AddPet(context.Background(), petstore.NewPet{Name: "Fido", Tag: ptr("dog")}) if err != nil { panic(err) } defer newPetResp.Body.Close() var created petstore.Pet json.NewDecoder(newPetResp.Body).Decode(&created) fmt.Printf("Created pet #%d\n", created.ID) // Output: Created pet #1000 } func ptr[T any](v T) *T { return &v } ``` ``` -------------------------------- ### Run oapi-codegen Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/README.md Use the go generate command to run the oapi-codegen tool. This command is typically placed in a //go:generate comment. ```go //go:generate go run github.com/oapi-codegen/oapi-codegen-exp/cmd/oapi-codegen ``` -------------------------------- ### Generating Standalone Runtime Packages with codegen.GenerateRuntime Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Employ `codegen.GenerateRuntime` to create separate runtime packages (`types`, `params`, `helpers`) for multiple generated specs. This reduces code duplication when you have many specs within a single module. The generated runtime code is written to specified directories and files. ```go package main import ( "fmt" "os" "path/filepath" "github.com/oapi-codegen/oapi-codegen-exp/codegen" ) func main() { rt, err := codegen.GenerateRuntime("github.com/org/project/runtime") if err != nil { panic(err) } subPkgs := []struct{ dir, file, code string }{ {"types", "types.gen.go", rt.Types}, {"params", "params.gen.go", rt.Params}, {"helpers", "helpers.gen.go", rt.Helpers}, } for _, sp := range subPkgs { dir := filepath.Join("./runtime", sp.dir) _ = os.MkdirAll(dir, 0755) _ = os.WriteFile(filepath.Join(dir, sp.file), []byte(sp.code), 0644) fmt.Printf("Generated %s/%s\n", sp.dir, sp.file) } // Output: // Generated types/types.gen.go // Generated params/params.gen.go // Generated helpers/helpers.gen.go } ``` -------------------------------- ### Send Webhooks with WebhookInitiator Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Use the generated WebhookInitiator to send webhook events to registered listeners. Ensure the server is configured with `webhook-initiator: true`. ```go // SERVER: send webhooks to registered listeners package main import ( "context" "log" "net/http" "github.com/google/uuid" doorbadge "github.com/oapi-codegen/oapi-codegen-exp/examples/webhook" ) type BadgeReader struct { initiator *doorbadge.WebhookInitiator webhooks map[uuid.UUID]string // id -> target URL } func main() { // WebhookInitiator is generated — one typed method per webhook operation initiator, _ := doorbadge.NewWebhookInitiator() // Send an enterEvent webhook to a registered listener person := doorbadge.Person{Name: "Alice"} resp, err := initiator.EnterEvent(context.Background(), "https://listener.example.com/hooks", person) if err != nil { log.Printf("webhook failed: %v", err) return } defer resp.Body.Close() log.Printf("webhook response: %d", resp.StatusCode) // Register webhook endpoint using generated HandlerFromMux reader := &BadgeReader{initiator: initiator, webhooks: make(map[uuid.UUID]string)} mux := http.NewServeMux() doorbadge.HandlerFromMux(reader, mux) // handles /api/webhook/{kind} and /api/webhook/{id} log.Fatal(http.ListenAndServe(":8080", mux)) } ``` -------------------------------- ### Handling Nullable Fields with Nullable[T] Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Demonstrates the use of `types.Nullable[T]` for three-state optional fields (unspecified, null, has value) when working with OpenAPI nullable fields. Shows setting values, nulls, and checking states. ```go package main import ( "encoding/json" "fmt" "github.com/oapi-codegen/oapi-codegen-exp/codegen/internal/runtime/types" ) type Profile struct { Name string `json:"name"` Nickname types.Nullable[string] `json:"nickname,omitempty"` } func main() { // --- Has a value --- p1 := Profile{Name: "Alice"} p1.Nickname.Set("Ace") b, _ := json.Marshal(p1) fmt.Println(string(b)) // Output: {"name":"Alice","nickname":"Ace"} v, _ := p1.Nickname.Get() fmt.Println(v) // Ace // --- Explicitly null --- p2 := Profile{Name: "Bob"} p2.Nickname.SetNull() b, _ = json.Marshal(p2) fmt.Println(string(b)) // Output: {"name":"Bob","nickname":null} fmt.Println(p2.Nickname.IsNull()) // true fmt.Println(p2.Nickname.IsSpecified()) // true // --- Unspecified (omitted) --- p3 := Profile{Name: "Carol"} // Nickname not set b, _ = json.Marshal(p3) fmt.Println(string(b)) // Output: {"name":"Carol"} fmt.Println(p3.Nickname.IsSpecified()) // false _, err := p3.Nickname.Get() fmt.Println(err) // nullable value is not specified // --- Unmarshal round-trip --- var p4 Profile json.Unmarshal([]byte(`{"name":"Dave","nickname":null}`), &p4) fmt.Println(p4.Nickname.IsNull()) // true } ``` -------------------------------- ### Filtering Operations and Schemas with output-options Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Configure `output-options` in your generation configuration to create multiple output files, such as separating public and internal APIs, by including specific tags and pruning unreferenced schemas. ```yaml # public-api.config.yaml — only public endpoints package: publicapi output: public.gen.go generation: server: chi client: true output-options: include-tags: [public] prune-unreferenced-schemas: true # drop schemas only used by excluded ops ``` ```yaml # internal-api.config.yaml — only internal endpoints package: internalapi output: internal.gen.go generation: server: chi output-options: include-tags: [internal] prune-unreferenced-schemas: true ``` -------------------------------- ### Generate std-http Server Interface Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Implement the `ServerInterface` for `std-http`. This involves creating a struct that satisfies the interface and registering it with `HandlerFromMux`. ```go package main import ( "encoding/json" "log" "net/http" "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded/stdhttp/server" petstore "github.com/oapi-codegen/oapi-codegen-exp/examples/petstore-expanded" ) // PetStore implements server.ServerInterface type PetStore struct { pets map[int64]petstore.Pet nextID int64 } func (p *PetStore) FindPets(w http.ResponseWriter, r *http.Request, params server.FindPetsParams) { var result []petstore.Pet for _, pet := range p.pets { result = append(result, pet) } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(result) } func (p *PetStore) AddPet(w http.ResponseWriter, r *http.Request) { var newPet petstore.NewPet if err := json.NewDecoder(r.Body).Decode(&newPet); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } pet := petstore.Pet{NewPet: newPet, ID: p.nextID} p.pets[p.nextID] = pet p.nextID++ w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(pet) } func (p *PetStore) FindPetByID(w http.ResponseWriter, r *http.Request, id int64) { pet, ok := p.pets[id] if !ok { http.Error(w, "not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(pet) } func (p *PetStore) DeletePet(w http.ResponseWriter, r *http.Request, id int64) { if _, ok := p.pets[id]; !ok { http.Error(w, "not found", http.StatusNotFound) return } delete(p.pets, id) w.WriteHeader(http.StatusNoContent) } func main() { store := &PetStore{pets: make(map[int64]petstore.Pet), nextID: 1} mux := http.NewServeMux() server.HandlerFromMux(store, mux) // registers all routes log.Fatal(http.ListenAndServe(":8080", mux)) } ``` -------------------------------- ### Generated Imports and Type Usage for External References Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Illustrates the Go import statements and type usage generated by `oapi-codegen` when `import-mapping` is configured, showing how external `$ref` types are integrated into your code. ```go // Generated code will produce imports like: import ( ext_a1b2c3 "github.com/org/project/common" // hash alias (auto) auth "github.com/org/project/auth" // explicit alias ) // And use them for external $ref types: type MyRequest struct { User ext_a1b2c3.User `json:"user"` Token auth.Token `json:"token"` } ``` -------------------------------- ### Generate Chi Router Handler Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Generates a Chi router handler by setting `server: chi` in the configuration. The generated `HandlerFromMux` function is compatible with `chi.Router`. ```yaml # server.config.yaml package: server generation: server: chi models-package: path: github.com/org/project/petstore alias: petstore ``` ```go package main import ( "log" "net/http" "github.com/go-chi/chi/v5" "github.com/org/project/petstore/chi/server" ) func main() { store := server.NewPetStore() // implements server.ServerInterface r := chi.NewRouter() server.HandlerFromMux(store, r) // binds all routes to the chi router log.Fatal(http.ListenAndServe(":8080", r)) } ``` -------------------------------- ### Generate Echo/v4 Server Handler Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Targets the Echo framework v4 by setting `server: echo/v4` in the configuration. The generated code uses `echo.Context` and the `RegisterHandlers` function binds routes to the Echo instance. ```yaml # server.config.yaml package: server generation: server: echo/v4 models-package: path: github.com/org/project/petstore alias: petstore ``` ```go package main import ( "log" "github.com/labstack/echo/v4" "github.com/org/project/petstore/echo-v4/server" ) func main() { store := server.NewPetStore() e := echo.New() server.RegisterHandlers(e, store) log.Fatal(e.Start(":8080")) } ``` -------------------------------- ### Command Line Execution for Filtered Output Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Execute the `oapi-codegen` command with different configuration files to generate distinct output files for different API facets, like public and internal interfaces. ```bash # In your generate.go or Makefile: oapi-codegen -config public-api.config.yaml api.yaml oapi-codegen -config internal-api.config.yaml api.yaml ``` -------------------------------- ### OpenAPI Extension Annotations for Code Generation Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Utilize OpenAPI extensions like `x-oapi-codegen-type-override`, `x-oapi-codegen-name-override`, `x-oapi-codegen-omitempty`, `x-oapi-codegen-skip-optional-pointer`, and `x-oapi-codegen-json-ignore` to customize Go type generation from OpenAPI specs. ```yaml # petstore-extended.yaml (excerpt) components: schemas: Money: type: string x-oapi-codegen-type-override: "decimal.Decimal;github.com/shopspring/decimal" Pet: required: [id, name] properties: id: type: integer format: int64 name: type: string x-oapi-codegen-name-override: PetName # override Go field name tag: type: string x-oapi-codegen-omitempty: true # force omitempty x-oapi-codegen-skip-optional-pointer: true # no *string wrapper internalNote: type: string x-oapi-codegen-json-ignore: true # json:"-" Severity: # OpenAPI 3.1 enum-via-oneOf: generates a proper Go enum type: integer oneOf: - title: HIGH const: 2 description: An urgent problem - title: MEDIUM const: 1 - title: LOW const: 0 description: Can wait forever # Generated Go: # type Severity int # const ( # HIGH Severity = 2 // An urgent problem # MEDIUM Severity = 1 # LOW Severity = 0 // Can wait forever # ) Tags: type: array items: type: string x-oapi-codegen-enum-varnames: [TagFoo, TagBar, TagBaz] ``` -------------------------------- ### Generate Code from OpenAPI Spec using CLI Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Use the `oapi-codegen` CLI to generate Go code from an OpenAPI specification file or URL. Options can be controlled via flags or a configuration file. ```bash # Minimal: generate models only (no server/client) into petstore.gen.go oapi-codegen -package petstore petstore-expanded.yaml # Full: use a config file that controls everything oapi-codegen -config config.yaml petstore-expanded.yaml # Load spec from URL oapi-codegen -config config.yaml https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.yaml # Generate a shared runtime package (types, params, helpers sub-packages) oapi-codegen --generate-runtime github.com/org/project/runtime --output ./runtime/ # => ./runtime/types/types.gen.go # => ./runtime/params/params.gen.go # => ./runtime/helpers/helpers.gen.go ``` -------------------------------- ### Resolving External Schema References with import-mapping Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Map spec file paths to Go import paths using `import-mapping` in your configuration to correctly resolve external `$ref`rences. Supports auto-aliasing, explicit aliasing, and keeping types in the same package. ```yaml # config.yaml import-mapping: ../common/types.yaml: github.com/org/project/common # auto alias ../auth/api.yaml: auth github.com/org/project/auth # explicit alias "auth" ./local-extras.yaml: "-" # same package ``` -------------------------------- ### oapi-codegen Generation Controls Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Configure which parts of the API specification to generate code for, including server frameworks, clients, webhooks, and callbacks. ```yaml generation: # Server framework to generate code for. # Supported: "std-http", "chi", "echo", "echo/v4", "gin", "gorilla", "fiber", "iris" # Default: "" (no server code generated) server: std-http # Generate an HTTP client that returns *http.Response. # Default: false client: true # Generate a SimpleClient wrapper with typed responses. # Requires client: true. # Default: false simple-client: true # Generate webhook initiator code (sends webhook requests to target URLs). # Generates a framework-agnostic client that takes the full target URL per-call. # Default: false webhook-initiator: true # Generate webhook receiver code (receives webhook requests). # Generates framework-specific handler functions. Requires server to be set. # Default: false webhook-receiver: true # Generate callback initiator code (sends callback requests to target URLs). # Default: false callback-initiator: true # Generate callback receiver code (receives callback requests). # Generates framework-specific handler functions. Requires server to be set. # Default: false callback-receiver: true ``` -------------------------------- ### Shared Runtime Package Configuration Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Configure oapi-codegen to use a shared runtime package for helper functions and custom types, reducing code duplication. The runtime package must be generated separately. ```yaml generation: runtime-package: path: github.com/org/project/runtime ``` -------------------------------- ### Applying Generated Default Values with ApplyDefaults() Source: https://context7.com/oapi-codegen/oapi-codegen-exp/llms.txt Generated structs include an `ApplyDefaults()` method. Call this method after unmarshaling to populate optional fields with values defined in the spec's `default:` properties. ```yaml # Example OpenAPI spec snippet with defaults: properties: name: type: string default: "Guest" age: type: integer default: 18 ``` -------------------------------- ### External Models Package Configuration Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Configure oapi-codegen to use model types from an external Go package instead of generating them locally. This requires specifying the path and optionally an alias for the package. ```yaml generation: models-package: path: github.com/org/project/models alias: models # optional, defaults to last segment of path ``` -------------------------------- ### oapi-codegen Output Filtering by Tags Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Control which operations are included or excluded based on their OpenAPI tags. Use 'include-tags' to specify which tags to include and 'exclude-tags' for tags to ignore. ```yaml output-options: # Only include operations tagged with one of these tags. Ignored when empty. include-tags: - public - beta # Exclude operations tagged with one of these tags. Ignored when empty. exclude-tags: - internal ``` -------------------------------- ### Generate Go Enum from OpenAPI `oneOf` + `const` Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/README.md This OpenAPI 3.1 schema idiom allows for named enums with per-value documentation. Ensure all branches have `const` and `title`, and the outer schema declares a scalar type. Set `generation.skip-enum-via-oneof: true` to disable this detection. ```yaml Severity: type: integer oneOf: - title: HIGH const: 2 description: An urgent problem - title: MEDIUM const: 1 - title: LOW const: 0 description: Can wait forever ``` -------------------------------- ### oapi-codegen Output Filtering by Operation IDs Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Filter generated code by specific operation IDs. Use 'include-operation-ids' to include only listed operations and 'exclude-operation-ids' to omit specified operations. ```yaml output-options: # Only include operations with one of these operation IDs. Ignored when empty. include-operation-ids: - listPets - createPet # Exclude operations with one of these operation IDs. Ignored when empty. exclude-operation-ids: - deprecatedEndpoint ``` -------------------------------- ### Enum Generation Control Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Disable the OpenAPI 3.1 enum-via-oneOf idiom detection. Set to true to retain legacy union output for schemas using this pattern. ```yaml generation: skip-enum-via-oneof: false ``` -------------------------------- ### oapi-codegen Schema Exclusion Source: https://github.com/oapi-codegen/oapi-codegen-exp/blob/main/Configuration.md Exclude specific schemas by name from being generated. This is useful for preventing the generation of internal or unused types. ```yaml output-options: # Exclude schemas with the given names from generation. Ignored when empty. exclude-schemas: - InternalConfig ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.