***

title: Use Go SDKs generated in Postman
max-toc-depth: 2
topictype: reference
---------------------

For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt. For full content including API reference and SDK examples, see https://learning.postman.com/llms-full.txt.

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.go` — `Environment` 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:

<Folder name="your-sdk" defaultOpen>
  <File name="README.md" comment="SDK documentation and usage instructions" />

  <File name="go.mod" comment="Go module definition and dependencies" />

  <File name=".gitignore" comment="Git ignore patterns for Go projects" />

  <Folder name=".devcontainer" defaultOpen>
    <File name="devcontainer.json" comment="VS Code development container configuration" />
  </Folder>

  <Folder name="cmd" defaultOpen>
    <Folder name="examples" defaultOpen>
      <File name="example.go" comment="Runnable example demonstrating SDK usage" />
    </Folder>
  </Folder>

  <Folder name="documentation" defaultOpen>
    <Folder name="services" defaultOpen>
      <File name="[ServiceName]_service.md" comment="Service-specific documentation" />
    </Folder>

    <Folder name="models" defaultOpen>
      <File name="[ModelName].md" comment="Model and type documentation" />
    </Folder>
  </Folder>

  <Folder name="pkg" defaultOpen>
    <Folder name="[sdkname]" defaultOpen>
      <File name="[sdkname].go" comment="Main SDK client" />
    </Folder>

    <Folder name="[sdkname]config" defaultOpen>
      <File name="config.go" comment="Config and RequestOption" />

      <File name="environments.go" comment="Environment constants" />
    </Folder>

    <Folder name="[servicename]" defaultOpen>
      <File name="[servicename]_service.go" comment="Service implementation with request methods" />

      <File name="[model_name].go" comment="Model structs and request param types" />

      <File name="request_params.go" comment="Request parameter definitions" />
    </Folder>

    <Folder name="shared" defaultOpen>
      <File name="[sdkname]_response.go" comment="Response wrappers" />
    </Folder>

    <Folder name="util" defaultOpen>
      <File name="to_pointer.go" comment="ToPointer helper functions" />

      <File name="nullable.go" comment="Nullable[T] type definitions" />
    </Folder>
  </Folder>

  <Folder name="internal" defaultOpen>
    <File name="[files]" comment="HTTP transport internals (not for direct use)" />
  </Folder>
</Folder>

## Example usage

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

<Tabs>
  <Tab title="Location">
    `cmd/examples/example.go`
  </Tab>

  <Tab title="Run the example">
    ```bash
    cd path/to/your-sdk
    go run cmd/examples/example.go
    ```
  </Tab>

  <Tab title="Example code structure">
    ```go
    package main

    import (
        "context"
        "fmt"

        "github.com/your-org/your-sdk/pkg/yoursdk"
        "github.com/your-org/your-sdk/pkg/yoursdkconfig"
        "github.com/your-org/your-sdk/pkg/users"
        "github.com/your-org/your-sdk/pkg/util"
    )

    func main() {
        config := yoursdkconfig.NewConfig()
        config.SetAccessToken("your-bearer-token")

        sdk := yoursdk.NewYourSdk(config)

        params := users.ListUsersRequestParams{
            Limit: util.ToPointer(int64(10)),
        }

        response, err := sdk.Users.ListUsers(context.Background(), params)
        if err != nil {
            panic(err)
        }

        fmt.Printf("%+v\n", response.Data)
    }
    ```
  </Tab>
</Tabs>

## 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:

```bash
go get github.com/your-org/your-sdk
```

Then import it in your code:

```go
import (
    "github.com/your-org/your-sdk/pkg/yoursdk"
    "github.com/your-org/your-sdk/pkg/yoursdkconfig"
)

config := yoursdkconfig.NewConfig()
sdk := 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:

```text
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](https://proxy.golang.org) and [pkg.go.dev](https://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](https://semver.org).

   ```bash
   git tag v1.0.0
   git push origin v1.0.0
   ```

3. The module is now available to any user using the following command:

   ```bash
   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:

```bash
# 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](https://pkg.go.dev).
* 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.

<Tabs>
  <Tab title="API Key">
    ```go
    config := yoursdkconfig.NewConfig()
    config.SetApiKey("your-api-key")

    sdk := yoursdk.NewYourSdk(config)
    ```
  </Tab>

  <Tab title="Bearer Token">
    ```go
    config := yoursdkconfig.NewConfig()
    config.SetAccessToken("your-bearer-token")

    sdk := yoursdk.NewYourSdk(config)
    ```
  </Tab>

  <Tab title="Basic Auth">
    ```go
    config := yoursdkconfig.NewConfig()
    config.SetUsername("your-username")
    config.SetPassword("your-password")

    sdk := yoursdk.NewYourSdk(config)
    ```
  </Tab>

  <Tab title="OAuth 2.0">
    ```go
    config := yoursdkconfig.NewConfig()
    config.SetClientId("your-client-id")
    config.SetClientSecret("your-client-secret")

    sdk := yoursdk.NewYourSdk(config)
    // SDK automatically handles token acquisition and refresh
    ```
  </Tab>
</Tabs>

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.

```go
response, err := sdk.Users.GetUser(context.Background(), "123")
if err != nil {
    fmt.Println("Status code:", err.Metadata.StatusCode)
    fmt.Println("Error:", err.Err)
    fmt.Println("Raw body:", string(err.Body))
    return
}

fmt.Println("User:", response.Data)
fmt.Println("Status code:", response.Metadata.StatusCode)
```

The `[SdkName]Error` wrapper contains the following fields:

| Field                 | Type                | Description                                                    |
| --------------------- | ------------------- | -------------------------------------------------------------- |
| `Err`                 | `error`             | The underlying error.                                          |
| `Data`                | `*T`                | Deserialized error response body (nil if unmarshaling failed). |
| `Body`                | `[]byte`            | Raw response body.                                             |
| `Metadata.StatusCode` | `int`               | HTTP status code.                                              |
| `Metadata.Headers`    | `map[string]string` | Response headers.                                              |

To handle specific status codes, run the following:

```go
response, sdkErr := sdk.Users.GetUser(context.Background(), "123")
if sdkErr != nil {
    switch sdkErr.Metadata.StatusCode {
    case 404:
        fmt.Println("User not found")
    case 403:
        fmt.Println("Permission denied")
    default:
        fmt.Println("API error:", sdkErr.Err)
    }
    return
}
```

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:

```go
response, sdkErr := sdk.Users.GetUser(context.Background(), "123")
if sdkErr != nil {
    if sdkErr.Metadata.StatusCode == 404 && sdkErr.Data != nil {
        fmt.Println("Message:", sdkErr.Data.Message)
        fmt.Println("Request ID:", sdkErr.Data.RequestId)
    }
    return
}
```

### Environment management

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

```go
// Use a named environment constant
config.SetEnvironment(yoursdkconfig.PRODUCTION_ENVIRONMENT)

// Or set a fully custom base URL
sdk.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.

```go
import (
    "context"
    "time"

    "github.com/your-org/your-sdk/pkg/yoursdk"
    "github.com/your-org/your-sdk/pkg/yoursdkconfig"
)

// 1. SDK level — default for all services and methods
config := yoursdkconfig.NewConfig()
config.SetBaseUrl("https://api.example.com")
config.SetTimeout(10 * time.Second)
sdk := yoursdk.NewYourSdk(config)

// 2. Service level — override for all methods in Users
sdk.Users.SetBaseUrl("https://legacy.api.example.com")
sdk.Users.SetTimeout(15 * time.Second)

// 3. Method level — override for GetUser only
sdk.Users.SetGetUserConfig(
    yoursdkconfig.WithBaseUrl("https://v2.api.example.com"),
)

// 4. Request level — override for this single call
response, err := sdk.Users.GetUser(
    context.Background(),
    "123",
    yoursdkconfig.WithTimeout(30*time.Second),
)
```

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

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

### Timeouts and retries

To set a global timeout, run the following:

```go
import "time"

config := yoursdkconfig.NewConfig()
sdk := yoursdk.NewYourSdk(config)

sdk.SetTimeout(10 * time.Second)
```

To configure retries through `RetryConfig`, run the following:

```go
retryConfig := yoursdkconfig.NewRetryConfig()
retryConfig.MaxAttempts = 5
retryConfig.RetryDelay = 200 * time.Millisecond
retryConfig.MaxDelay = 10 * time.Second
retryConfig.BackOffFactor = 2.0
retryConfig.RetryDelayJitter = 50 * time.Millisecond

config := yoursdkconfig.NewConfig()
config.SetRetryConfig(retryConfig)

sdk := yoursdk.NewYourSdk(config)
```

The default retry configuration is:

| Field                | Default                                                    |
| -------------------- | ---------------------------------------------------------- |
| `MaxAttempts`        | `3`                                                        |
| `RetryDelay`         | `150ms`                                                    |
| `MaxDelay`           | `5000ms`                                                   |
| `RetryDelayJitter`   | `50ms`                                                     |
| `BackOffFactor`      | `2.0`                                                      |
| `HttpMethodsToRetry` | `GET`, `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:

```go
newUser := users.NewUser{}
newUser.SetUsername("ab") // fails if spec requires minLength: 3

response, err := sdk.Users.CreateUser(context.Background(), newUser)
if err != nil {
    // err.Err contains the validation message
    fmt.Println("Validation failed:", err.Err)
    // response is nil
}
```

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:

```go
import "github.com/your-org/your-sdk/pkg/util"

params := users.ListUsersRequestParams{
    Limit:  util.ToPointer(int64(10)),   // included in request
    SortBy: util.ToPointer("name"),      // included in request
    // Page omitted — excluded from request entirely
}
```

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

```go
// Present with a value
bio := util.Nullable[string]{Value: "hello world", IsNull: false}

// Explicitly null — sends "null" in JSON
notes := util.Nullable[string]{IsNull: true}
```

The following examples show the full range of field combinations:

```go
// Example 1: All fields set
user := users.NewUser{
    Username: "alice",                                          // required non-nullable
    Age:      util.ToPointer(int64(30)),                       // optional non-nullable
    Bio:      util.Nullable[string]{Value: "hello"},           // optional nullable with value
    NickName: util.Nullable[string]{IsNull: true},             // optional nullable set to null
}
// JSON sent to server:
// {"username":"alice","age":30,"bio":"hello","nickName":null}

// Example 2: Minimal — only required fields
minimalUser := users.NewUser{
    Username: "bob",
}
// JSON sent to server:
// {"username":"bob"}
// Optional fields are completely omitted

// Example 3: Mixed — some optional fields set, others omitted
mixedUser := users.NewUser{
    Username: "carol",
    Bio:      util.Nullable[string]{Value: "engineer"},        // present
    NickName: util.Nullable[string]{IsNull: true},             // explicitly null
    // Age omitted — not sent
}
// JSON sent to server:
// {"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`.