Generating Go SDKs from OpenAPI
Turn OpenAPI operations into a Go client you own.Generate Go clients with models, resource methods, authentication, and typed responses. The output uses only the Go standard library.
Generate a client
Import generator/sdk and generator/sdk/gosdk from github.com/pb33f/libopenapi.
With a parsed v3 model:
result, err := gosdk.Generate(&model.Model, gosdk.Options{
PackageName: "catalog",
Prepare: sdk.PrepareOptions{
Operations: []string{"listProducts"},
Names: map[string]sdk.OperationName{
"listProducts": {Resource: "Products", Method: "List"},
},
},
})
if err != nil {
return err
}
Use your API’s operation IDs. Omit Operations to include every operation with an operationId.
Check result.Diagnostics, then write each result.Files entry using its Path and Content.
| File | Contents |
|---|---|
models.gen.go |
Request and response models. |
client.gen.go |
HTTP client, credentials, and errors. |
resources.gen.go |
Methods such as client.Products.List. |
Use the client
For listProducts with no parameters or body, using your generated catalog package:
client, err := catalog.NewClient("https://api.example.com")
if err != nil {
return err
}
response, err := client.Products.List(ctx)
if err != nil {
return err
}
fmt.Println(response.StatusCode, response.Value)
Parameters and request bodies go in a generated *ProductsListParams; the body uses its Body
field. Responses include Value, StatusCode, and Header. Use errors.As for *catalog.APIError;
its Value holds a declared JSON error and Body holds the raw bytes.
Configure it
Pass options to NewClient. Credentials use the security scheme name from your spec:
catalog.WithCredential("apiToken", catalog.BearerToken(os.Getenv("API_TOKEN")))
Basic auth, API keys, OAuth/OpenID bearer tokens, and mutual TLS are also supported.
Use WithHTTPClient for your own transport, WithTimeout for the default client’s timeout,
and WithMaxResponseBody to change the 8 MiB response limit. A supplied client owns its redirect
and TLS policy.
Optional nullable request fields use nil to omit, catalog.Null[T]() for null, and
catalog.NullableValue(value) for a value. Model options go in gosdk.Options.Models.
Limits
Supports JSON bodies and scalar/array path, query, and header parameters. Unsupported wire behavior returns a generation error: this includes multipart, streaming, binary downloads, object parameters, and non-JSON success bodies.
For single-step Arazzo helpers, use sdk.Prepare, sdk.PrepareArazzo, and gosdk.GenerateContract.
See the SDK package’s README.md for the supported workflow subset and full HTTP limits.
Need models only? See Generating Code or Generating TypeScript.