> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt.

# Use Go SDKs generated in Postman

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:

## Example usage

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

#### Location

`cmd/examples/example.go`

#### Run the example

```bash
cd path/to/your-sdk
go run cmd/examples/example.go
```

#### 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)
}
```

## 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 publish your generated Go SDK, see [Publish Go SDKs generated in Postman](/docs/sdk-generator/publish/go-manual/).

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

#### API Key

```go
config := yoursdkconfig.NewConfig()
config.SetApiKey("your-api-key")

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

#### Bearer Token

```go
config := yoursdkconfig.NewConfig()
config.SetAccessToken("your-bearer-token")

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

#### Basic Auth

```go
config := yoursdkconfig.NewConfig()
config.SetUsername("your-username")
config.SetPassword("your-password")

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

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

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`.