> 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 TypeScript SDKs generated in Postman

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

## SDK structure

The TypeScript SDK includes the following key files:

* `src/index.ts` — Main entry point, exports SDK client, services, and models.
* `src/services/` — Service classes organized in directories alongside their models.
* `src/http/` — HTTP client, error types, handler chain, hooks, and transport layer.
* `package.json` — Dependencies vary by transport (fetch built-in, or axios).

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

## Example usage

Each generated SDK includes an `examples/` directory with a working project demonstrating SDK usage.

The example includes the following features:

* SDK initialization with authentication
* Making API calls to various endpoints
* Error handling patterns
* Working with typed request/response models

#### Location

`examples/src/index.ts`

#### Run the example

```bash
cd examples
npm install
npm start
```

#### Example code structure

```typescript
import { YourSdk } from 'your-sdk-package';

(async () => {
// Initialize the SDK
const sdk = new YourSdk({
    apiKey: 'your-api-key',
    baseUrl: 'https://api.example.com'
});

try {
    // Call an API endpoint
    const result = await sdk.users.getUser({ userId: '123' });
    console.log('User:', result);
} catch (error) {
    console.error('Error:', error);
}
})();
```

## Import the TypeScript SDK locally

You can import the generated SDK using npm, by file path, or using a workspace (for monorepos). Below are instructions for each method.

### Import using npm link

You can use `npm link` to create a symlink to the generated SDK, allowing you to import it as if it were installed from npm.

1. Run the following commands in the SDK directory:

   ```bash
   cd path/to/your-sdk
   npm install
   npm run build
   npm link
   ```

   Alternatively, run the following commands in your project directory:

   ```bash
   cd path/to/your-project
   npm link your-sdk-package-name
   ```

2. Use the SDK in your code.

   ```typescript
   import { YourSdk } from 'your-sdk-package-name';

   const sdk = new YourSdk({ apiKey: 'test' });
   ```

### Import using a file path

To import the SDK from a local path, you can either install it using npm or add it as a dependency in your `package.json`.

* Using npm:

  ```bash
  npm install ../path/to/your-sdk
  ```

* Adding to package.json:

  ```json
  {
  "dependencies": {
      "your-sdk": "file:../path/to/your-sdk"
  }
  }
  ```

### Import using workspaces (for monorepos)

To import using workspaces, add the SDK path to the `workspaces` array in your root `package.json`:

```json
{
  "workspaces": [
    "packages/*",
    "path/to/your-sdk"
  ]
}
```

## Publish

To publish your generated TypeScript SDK, see [Publish TypeScript SDKs generated in Postman](/docs/sdk-generator/publish/typescript-manual/).

## Advanced usage

You can further customize the SDK by modifying the generated code, adding new features, or integrating it with your existing codebase. Here are some advanced topics to explore.

### Authentication

The SDK supports various authentication methods. You can configure authentication when initializing the SDK client.

#### API Key

```typescript
const sdk = new YourSdk({
token: 'your-bearer-token'
});
```

#### Bearer Token

```python
sdk = YourSdk(access_token="your-bearer-token")
```

#### Basic Auth

```typescript
const sdk = new YourSdk({
username: 'your-username',
password: 'your-password'
});
```

#### OAuth 2.0 (Client Credentials)

```typescript
const sdk = new YourSdk({
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
});

// SDK automatically handles token refresh
const result = await sdk.users.getUser({ userId: '123' });
```

#### OAuth 2.0 (Access Token)

```typescript
const sdk = new YourSdk({
accessToken: 'your-access-token'
});
```

### Environment management

The SDK supports multiple environments (for example, production, staging) with different base URLs.

```typescript
import { YourSdk, Environment } from 'your-sdk';

const sdk = new YourSdk({
  environment: Environment.PRODUCTION,
  apiKey: 'your-api-key'
});

// Or use custom base URL
const sdk = new YourSdk({
  baseUrl: 'https://custom.api.example.com',
  apiKey: 'your-api-key'
});
```

### Error handling

The SDK raises custom exceptions for API errors, which include details about the error message, status code, and response body. You can catch these exceptions to handle errors in your application.

To handle errors, do the following:

```typescript
import { YourSdk, HttpError, ValidationError } from 'your-sdk';

const sdk = new YourSdk({ apiKey: 'your-api-key' });

try {
  const user = await sdk.users.getUser({ userId: '123' });
  console.log(user);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message);
  } else if (error instanceof HttpError) {
    console.error('HTTP error:', error.message);
    console.error('Status code:', error.metadata.status);
    console.error('Response:', error.raw);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

To handle specific error codes, do the following:

```typescript
try {
  await sdk.users.deleteUser({ userId: '123' });
} catch (error) {
  if (error instanceof HttpError) {
    switch (error.metadata.status) {
      case 404:
        console.log('User not found');
        break;
      case 403:
        console.log('Permission denied');
        break;
      default:
        console.log('HTTP error:', error.message);
    }
  }
}
```

### Timeouts and retries

To set a global timeout, do the following:

```typescript
const sdk = new YourSdk({
  apiKey: 'your-api-key',
  timeoutMs: 10000 // 10 seconds
});
```

To set a per-request timeout, do the following:

Config can be overridden per-request using `requestConfig`:

```typescript
const user = await sdk.users.getUser(
  { userId: '123' },
  { timeoutMs: 5000 } // 5 seconds for this request only
);
```

To configure retries, do the following:

```typescript
const sdk = new YourSdk({
  apiKey: 'your-api-key',
  retry: {
    attempts: 3,
    delayMs: 1000,         // 1 second between retries
    maxDelayMs: 30000,     // max delay cap
    backoffFactor: 2,      // exponential backoff multiplier
    jitterMs: 100,         // random jitter
    statusCodesToRetry: [408, 429, 500, 502, 503, 504],
    httpMethodsToRetry: ['GET', 'POST', 'PUT', 'DELETE']
  }
});
```

## Additional resources

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

* SDK documentation — Check the `documentation/` directory in your SDK for detailed docs on services, models, and code snippets.
* Type definitions — All models and services are fully typed.
* Example usage — Refer to the `examples/` directory for working code samples demonstrating how to use the SDK in different scenarios.
* Dependencies — (vary by transport selection):
  * fetch (built-in) or axios: HTTP client
  * zod: Runtime validation (when response validation is enabled)