Use TypeScript SDKs generated in Postman

View as Markdown

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:

your-sdk
README.md# Main documentation
package.json# npm package configuration
tsconfig.json# TypeScript configuration
.gitignore# Git ignore rules
LICENSE# License file
.env.example# Example environment file
.devcontainer
scripts
src
examples
documentation

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

examples/src/index.ts

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.

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:

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

    Alternatively, run the following commands in your project directory:

    $cd path/to/your-project
    $npm link your-sdk-package-name
  2. Use the SDK in your code.

    1import { YourSdk } from 'your-sdk-package-name';
    2
    3const 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:

    $npm install ../path/to/your-sdk
  • Adding to package.json:

    1{
    2"dependencies": {
    3 "your-sdk": "file:../path/to/your-sdk"
    4}
    5}

Import using workspaces (for monorepos)

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

1{
2 "workspaces": [
3 "packages/*",
4 "path/to/your-sdk"
5 ]
6}

Publish

To publish your generated TypeScript SDK, see Publish TypeScript SDKs generated in Postman.

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.

1const sdk = new YourSdk({
2token: 'your-bearer-token'
3});

Environment management

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

1import { YourSdk, Environment } from 'your-sdk';
2
3const sdk = new YourSdk({
4 environment: Environment.PRODUCTION,
5 apiKey: 'your-api-key'
6});
7
8// Or use custom base URL
9const sdk = new YourSdk({
10 baseUrl: 'https://custom.api.example.com',
11 apiKey: 'your-api-key'
12});

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:

1import { YourSdk, HttpError, ValidationError } from 'your-sdk';
2
3const sdk = new YourSdk({ apiKey: 'your-api-key' });
4
5try {
6 const user = await sdk.users.getUser({ userId: '123' });
7 console.log(user);
8} catch (error) {
9 if (error instanceof ValidationError) {
10 console.error('Validation failed:', error.message);
11 } else if (error instanceof HttpError) {
12 console.error('HTTP error:', error.message);
13 console.error('Status code:', error.metadata.status);
14 console.error('Response:', error.raw);
15 } else {
16 console.error('Unexpected error:', error);
17 }
18}

To handle specific error codes, do the following:

1try {
2 await sdk.users.deleteUser({ userId: '123' });
3} catch (error) {
4 if (error instanceof HttpError) {
5 switch (error.metadata.status) {
6 case 404:
7 console.log('User not found');
8 break;
9 case 403:
10 console.log('Permission denied');
11 break;
12 default:
13 console.log('HTTP error:', error.message);
14 }
15 }
16}

Timeouts and retries

To set a global timeout, do the following:

1const sdk = new YourSdk({
2 apiKey: 'your-api-key',
3 timeoutMs: 10000 // 10 seconds
4});

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

Config can be overridden per-request using requestConfig:

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

To configure retries, do the following:

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

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)