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
package.json
tsconfig.json
.gitignore
LICENSE
.env.example
.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 npm

To share your generated TypeScript SDK with the community, you can publish it to npm. This allows other developers to easily install it using npm. Follow the steps below.

Prerequisites

To publish your SDK to npm, you need the following:

  • An npm account. You can create it at npmjs.com.
  • npm CLI installed. You can install it with Node.js from nodejs.org.
  • A unique package name. You can check availability using the npm search your-package-name command.

Publish your TypeScript SDK to npm

  1. Configure package.json. Ensure these fields are set correctly:

    1{
    2"name": "@your-org/your-sdk",
    3"version": "1.0.0",
    4"description": "SDK for Your API",
    5"main": "dist/index.js",
    6"types": "dist/index.d.ts",
    7"files": [
    8 "dist",
    9 "README.md",
    10 "LICENSE"
    11],
    12"repository": {
    13 "type": "git",
    14 "url": "https://github.com/your-org/your-sdk"
    15},
    16"keywords": ["api", "sdk", "your-api"],
    17"author": "Your Name",
    18"license": "MIT"
    19}
  2. Build the SDK.

    $npm install
    $npm run build
    $npm test
  3. Log in to npm.

    $npm login
  4. Publish the package.

    • For public packages, use:

      $npm publish --access public
    • For scoped private packages, use:

      $npm publish
  5. Verify publication:

    $npm info @your-org/your-sdk

Publish updates

To publish an updated SDK, update the version in the package.json following the semantic versioning:

  • Patch: 1.0.01.0.1 (bug fixes)
  • Minor: 1.0.01.1.0 (new features, backward compatible)
  • Major: 1.0.02.0.0 (breaking changes)

Alternatively, you can use the npm version command:

$npm version patch # or minor, or major
$npm publish

Best practices for publishing TypeScript SDKs

Use the following best practices when publishing your TypeScript SDK to npm:

  • Use .npmignore to exclude unnecessary files.
  • Include a comprehensive README.md.
  • Add a LICENSE file.
  • Tag releases in Git: git tag v1.0.0 && git push --tags.
  • Set up CI/CD for automated publishing.
  • Consider using np tool for streamlined publishing: npx np.

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)