Use Go SDKs generated in Postman

View as Markdown

This guide provides instructions for using Go SDKs generated by Postman SDK Generator. It covers how to install the SDK into your project, run example code, and best practices for using the SDK effectively in your applications.

SDK structure

The Go SDK includes the following key files:

  • pkg/[sdkname]/[sdkname].go — The main SDK client, instantiated with a Config.
  • pkg/[servicename]/[servicename]_service.go — Service files with request methods.
  • pkg/[servicename]/[model_name].go — Model structs and request parameter types.
  • pkg/[sdkname]config/config.go — Configuration types (Config, RetryConfig, RequestOption).
  • pkg/[sdkname]config/environments.goEnvironment type and server constants.
  • pkg/shared/[sdkname]_response.go — Response wrappers ([SdkName]Response[T], [SdkName]Error[T]).
  • pkg/util/to_pointer.go — The ToPointer helper.
  • pkg/util/nullable.go — The Nullable[T] type.
  • internal/ — An internal HTTP transport and config management (not for direct use).
  • go.mod — Go module definition.
  • cmd/examples/example.go — Runnable example demonstrating SDK usage.

The following is an example of the typical structure of a generated Go SDK:

your-sdk
README.md
go.mod
.gitignore
.devcontainer
devcontainer.json
cmd
examples
example.go
documentation
services
[ServiceName]_service.md
models
[ModelName].md
pkg
[sdkname]
[sdkname].go
[sdkname]config
config.go
environments.go
[servicename]
[servicename]_service.go
[model_name].go
request_params.go
shared
[sdkname]_response.go
util
to_pointer.go
nullable.go
internal
[files]

Example usage

Each generated SDK includes a cmd/examples/example.go file demonstrating SDK initialization, making an API call, and basic error handling.

cmd/examples/example.go

Install the Go SDK

To use the generated Go SDK in your project, you can either install it from a public registry (like GitHub) or use a local path if it’s not yet published.

Install using go get

To install the SDK and add it to your module, run:

$go get github.com/your-org/your-sdk

Then import it in your code:

1import (
2 "github.com/your-org/your-sdk/pkg/yoursdk"
3 "github.com/your-org/your-sdk/pkg/yoursdkconfig"
4)
5
6config := yoursdkconfig.NewConfig()
7sdk := yoursdk.NewYourSdk(config)

Install from a local path

If you are working with an SDK that is not yet published to a registry, use a replace directive in your go.mod to point to the local directory:

module your-app
go 1.22
require github.com/your-org/your-sdk v0.0.0
replace github.com/your-org/your-sdk => ../path/to/your-sdk

Then run go mod tidy to resolve dependencies.

Publish to a Go module registry

Go modules are distributed through version control. Publishing your SDK makes it available using go get through the Go module proxy and pkg.go.dev.

Prerequisites

To publish your SDK, you need the following:

  • A public Git repository (for example, GitHub or GitLab).
  • The module path in go.mod must match the repository URL (for example, module github.com/your-org/your-sdk).

Publish your Go SDK

To publish your SDK, do the following:

  1. Push your SDK to a public Git repository.

  2. Tag a release using semantic versioning.

    $git tag v1.0.0
    $git push origin v1.0.0
  3. The module is now available to any user using the following command:

    $go get github.com/your-org/your-sdk@v1.0.0
  4. Verify the publication at https://pkg.go.dev/github.com/your-org/your-sdk. Documentation is generated automatically from exported Go doc comments.

Publish updates

To publish updates to your SDK, run the following:

$# Tag a new version
$git tag v1.0.1
$git push origin v1.0.1

Best practices for publishing Go SDKs

Use the following best practices when publishing your Go SDK:

  • Use semantic versioning with major version bumps for breaking changes.
  • For v2 and later, update the module path in go.mod to include the major version suffix (for example, module github.com/your-org/your-sdk/v2).
  • Write Go doc comments on all exported types and functions. They become the SDK’s documentation on Go Packages.
  • Tag releases in Git rather than publishing snapshots.

Advanced usage

Authentication

The SDK supports various authentication methods. Configure authentication on the Config before constructing the SDK client.

The SDK includes authentication support based on the security schemes defined in your API specification. The following examples show the possible authentication methods.

1config := yoursdkconfig.NewConfig()
2config.SetApiKey("your-api-key")
3
4sdk := yoursdk.NewYourSdk(config)

To update credentials after initialization, call the same setter methods on the config. Each generated auth setter is only present when the corresponding auth type is defined in the specification.

Error handling

Service methods return a pair of (*[SdkName]Response[T], *[SdkName]Error[E]). Exactly one of the two will be non-nil. Check the error before accessing the response.

1response, err := sdk.Users.GetUser(context.Background(), "123")
2if err != nil {
3 fmt.Println("Status code:", err.Metadata.StatusCode)
4 fmt.Println("Error:", err.Err)
5 fmt.Println("Raw body:", string(err.Body))
6 return
7}
8
9fmt.Println("User:", response.Data)
10fmt.Println("Status code:", response.Metadata.StatusCode)

The [SdkName]Error wrapper contains the following fields:

FieldTypeDescription
ErrerrorThe underlying error.
Data*TDeserialized error response body (nil if unmarshaling failed).
Body[]byteRaw response body.
Metadata.StatusCodeintHTTP status code.
Metadata.Headersmap[string]stringResponse headers.

To handle specific status codes, run the following:

1response, sdkErr := sdk.Users.GetUser(context.Background(), "123")
2if sdkErr != nil {
3 switch sdkErr.Metadata.StatusCode {
4 case 404:
5 fmt.Println("User not found")
6 case 403:
7 fmt.Println("Permission denied")
8 default:
9 fmt.Println("API error:", sdkErr.Err)
10 }
11 return
12}

When the API specification defines typed error response models (for example, a NotFoundError schema on a 404 response), the SDK generates a corresponding model struct in the service package. Access its fields through the Data field of the error:

1response, sdkErr := sdk.Users.GetUser(context.Background(), "123")
2if sdkErr != nil {
3 if sdkErr.Metadata.StatusCode == 404 && sdkErr.Data != nil {
4 fmt.Println("Message:", sdkErr.Data.Message)
5 fmt.Println("Request ID:", sdkErr.Data.RequestId)
6 }
7 return
8}

Environment management

The SDK generates an Environment type with constants for each named server defined in your API specification.

1// Use a named environment constant
2config.SetEnvironment(yoursdkconfig.PRODUCTION_ENVIRONMENT)
3
4// Or set a fully custom base URL
5sdk.SetBaseUrl("https://staging.api.example.com")

Available environment constants are defined in pkg/[sdkname]config/environments.go.

Hierarchical configuration

Go supports four levels of configuration. Each level overrides the previous, with request-level being the most specific.

1import (
2 "context"
3 "time"
4
5 "github.com/your-org/your-sdk/pkg/yoursdk"
6 "github.com/your-org/your-sdk/pkg/yoursdkconfig"
7)
8
9// 1. SDK level — default for all services and methods
10config := yoursdkconfig.NewConfig()
11config.SetBaseUrl("https://api.example.com")
12config.SetTimeout(10 * time.Second)
13sdk := yoursdk.NewYourSdk(config)
14
15// 2. Service level — override for all methods in Users
16sdk.Users.SetBaseUrl("https://legacy.api.example.com")
17sdk.Users.SetTimeout(15 * time.Second)
18
19// 3. Method level — override for GetUser only
20sdk.Users.SetGetUserConfig(
21 yoursdkconfig.WithBaseUrl("https://v2.api.example.com"),
22)
23
24// 4. Request level — override for this single call
25response, err := sdk.Users.GetUser(
26 context.Background(),
27 "123",
28 yoursdkconfig.WithTimeout(30*time.Second),
29)

Available RequestOption constructors mirror the Config setters and are defined in pkg/[sdkname]config/config.go:

1yoursdkconfig.WithBaseUrl("https://...")
2yoursdkconfig.WithTimeout(30 * time.Second)
3yoursdkconfig.WithRetryConfig(retryConfig)
4yoursdkconfig.WithAccessToken("new-token") // generated per auth type

Timeouts and retries

To set a global timeout, run the following:

1import "time"
2
3config := yoursdkconfig.NewConfig()
4sdk := yoursdk.NewYourSdk(config)
5
6sdk.SetTimeout(10 * time.Second)

To configure retries through RetryConfig, run the following:

1retryConfig := yoursdkconfig.NewRetryConfig()
2retryConfig.MaxAttempts = 5
3retryConfig.RetryDelay = 200 * time.Millisecond
4retryConfig.MaxDelay = 10 * time.Second
5retryConfig.BackOffFactor = 2.0
6retryConfig.RetryDelayJitter = 50 * time.Millisecond
7
8config := yoursdkconfig.NewConfig()
9config.SetRetryConfig(retryConfig)
10
11sdk := yoursdk.NewYourSdk(config)

The default retry configuration is:

FieldDefault
MaxAttempts3
RetryDelay150ms
MaxDelay5000ms
RetryDelayJitter50ms
BackOffFactor2.0
HttpMethodsToRetryGET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS

Validation

The SDK generates validators that enforce OpenAPI constraints at runtime. Validation happens automatically when making API calls. The SDK validates parameters and request bodies before sending the request.

Supported constraints include: minLength, maxLength, pattern, minimum, maximum, multipleOf, minItems, maxItems, and uniqueItems.

If validation fails, the service method returns a non-nil error and the request isn’t sent:

1newUser := users.NewUser{}
2newUser.SetUsername("ab") // fails if spec requires minLength: 3
3
4response, err := sdk.Users.CreateUser(context.Background(), newUser)
5if err != nil {
6 // err.Err contains the validation message
7 fmt.Println("Validation failed:", err.Err)
8 // response is nil
9}

No manual validation calls are needed.

Optional and nullable field handling

The SDK uses two distinct types to represent optional and nullable fields, providing clear distinction between undefined, null, and present values. This is important when building request models, as omitting an optional field versus explicitly setting it to null produces different JSON payloads.

Optional non-nullable fields use Go pointer types (*T). Use util.ToPointer to create a pointer from a literal value:

1import "github.com/your-org/your-sdk/pkg/util"
2
3params := users.ListUsersRequestParams{
4 Limit: util.ToPointer(int64(10)), // included in request
5 SortBy: util.ToPointer("name"), // included in request
6 // Page omitted — excluded from request entirely
7}

Optional or required nullable fields use util.Nullable[T]. This wrapper explicitly distinguishes between absent, null, and valued states:

1// Present with a value
2bio := util.Nullable[string]{Value: "hello world", IsNull: false}
3
4// Explicitly null — sends "null" in JSON
5notes := util.Nullable[string]{IsNull: true}

The following examples show the full range of field combinations:

1// Example 1: All fields set
2user := users.NewUser{
3 Username: "alice", // required non-nullable
4 Age: util.ToPointer(int64(30)), // optional non-nullable
5 Bio: util.Nullable[string]{Value: "hello"}, // optional nullable with value
6 NickName: util.Nullable[string]{IsNull: true}, // optional nullable set to null
7}
8// JSON sent to server:
9// {"username":"alice","age":30,"bio":"hello","nickName":null}
10
11// Example 2: Minimal — only required fields
12minimalUser := users.NewUser{
13 Username: "bob",
14}
15// JSON sent to server:
16// {"username":"bob"}
17// Optional fields are completely omitted
18
19// Example 3: Mixed — some optional fields set, others omitted
20mixedUser := users.NewUser{
21 Username: "carol",
22 Bio: util.Nullable[string]{Value: "engineer"}, // present
23 NickName: util.Nullable[string]{IsNull: true}, // explicitly null
24 // Age omitted — not sent
25}
26// JSON sent to server:
27// {"username":"carol","bio":"engineer","nickName":null}

Additional resources

Consider the following resources for using and customizing your Go SDK:

  • SDK documentation — Check the documentation/ directory inside your SDK for per-service and per-model reference pages.
  • Go doc — Run go doc ./... in your SDK directory to browse documentation in the terminal.
  • Go Packages — Once published, your SDK documentation is available at https://pkg.go.dev/github.com/your-org/your-sdk.
  • Example usage — See cmd/examples/example.go for a runnable demonstration of the SDK.
  • Dependencies — The SDK uses only the Go standard library and requires Go >= 1.19.0.