Use Python SDKs generated in Postman

View as Markdown

This guide provides instructions for using Python 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.

The Postman SDK Generator creates Python SDKs with type-safe models, service classes for API endpoints, authentication handling, error handling, and comprehensive documentation to help you integrate with your API quickly and efficiently. Models are validated using Pydantic v2, providing runtime type checking, serialization, and clear validation error messages out of the box.

SDK structure

Generated Python SDKs include the following key components:

  • Core clients — sdk.py for synchronous operations and sdk_async.py for asynchronous work
  • Service layer — Organized in services/ with async variants in services/async_/
  • Data models — Type-validated classes in models/ powered by Pydantic v2
  • Network infrastructure — Located in net/ directory handling configuration, transport, request chains, and authentication
  • Dependencies — Specified in pyproject.toml (requests, pydantic >=2.0) The directory structure includes documentation files, example implementations, and installation scripts for both Unix and Windows environments.

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

your-sdk
README.md
PyPI_README.md
pyproject.toml
.gitignore
LICENSE
.env.example
install.sh
install.cmd
.devcontainer
src
examples
documentation

Type safety with Pydantic

Generated models extend Pydantic’s BaseModel, giving you automatic validation, serialization, and clear error messages without any additional setup.

Model validation

Fields are validated at instantiation. Passing an incorrect type raises a ValidationError with a detailed description of what went wrong:

1from pydantic import ValidationError
2from your_sdk.models import Pet
3
4# Valid usage
5pet = Pet(name="Fluffy", status="available")
6
7# Invalid usage — raises ValidationError
8try:
9 pet = Pet(name=123, status="available")
10except ValidationError as e:
11 print(e)
12 # 1 validation error for Pet
13 # name
14 # Input should be a valid string [type=string_type]

Optional and nullable fields

The SDK distinguishes between fields that are not set and fields explicitly set to None. Only fields you provide are included in API requests:

1from your_sdk.models import UpdateContainerGroup
2
3# Only `replicas` and `country_codes` are sent in the request body.
4# `liveness_probe` is sent as null because it was explicitly set to None.
5# Unset fields like `display_name` are omitted entirely.
6container = UpdateContainerGroup(
7 replicas=2,
8 country_codes=["us"],
9 liveness_probe=None, # sent as null
10)

Serialization

Models serialize to API-compatible dictionaries using model_dump_original(), which applies field aliases, excludes unset fields, and maps Python snake_case names to their original API names:

1pet = Pet(name="Fluffy", status="available")
2
3# Serializes using the API field names (aliases)
4payload = pet.model_dump_original()
5# {"name": "Fluffy", "status": "available"}

Extra fields

Models accept additional properties not defined in the schema (useful for forward compatibility). Extra fields are accessible through _kwargs but are excluded from serialization so they’re never sent to the API:

1pet = Pet(name="Fluffy", status="available", undocumented_field="value")
2
3pet._kwargs # {"undocumented_field": "value"}
4pet.model_dump_original() # {"name": "Fluffy", "status": "available"}

Example usage

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

The example includes the following features:

  • Both sync and async usage patterns (async services under services/async_/)
  • SDK configuration
  • Type-safe API calls
  • Error handling with custom exceptions

examples/sample.py

Import the Python SDK locally

You can import the generated SDK into your Python project using pip, Poetry, or by adding it to your PYTHONPATH. Below are instructions for each method.

Import using pip with editable install

To import the SDK using pip in editable mode, do the following:

  1. Install the SDK in editable mode.

    $cd path/to/your-sdk
    $pip install -e .
  2. Use the SDK in your code.

    1from your_sdk import YourSdk
    2
    3sdk = YourSdk(api_key="test")

Changes to the SDK source reflect immediately, without reinstalling.

Import using pip with file path

To import the SDK using pip with a local file path, do the following:

$pip install path/to/your-sdk

To import the SDK in requirements.txt, add the following line:

your-sdk @ file:///absolute/path/to/your-sdk

Import by adding to PYTHONPATH

Tom import the SDK by adding it to your PYTHONPATH, do the following:

  1. Set the PYTHONPATH environment variable:

    $export PYTHONPATH="${PYTHONPATH}:/path/to/your-sdk/src"
  2. Use the SDK in your code:

    1from your_sdk import YourSdk

Import using Poetry

To import the SDK using Poetry, add it as a dependency with a local path:

$poetry add ../path/to/your-sdk

To import the SDK in pyproject.toml, add the following line to the [tool.poetry.dependencies] section:

1[tool.poetry.dependencies]
2your-sdk = { path = "../path/to/your-sdk", develop = true }

Publish to PyPI

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

Prerequisites

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

  • PyPI account (create at pypi.org)
  • Twine installed: pip install twine

Configure pyproject.toml

Ensure your SDK’s pyproject.toml is properly configured:

1[build-system]
2requires = ["setuptools>=61.0", "wheel"]
3build-backend = "setuptools.build_meta"
4
5[project]
6name = "your-sdk"
7version = "1.0.0"
8description = "SDK for Your API"
9readme = "README.md"
10requires-python = ">=3.9"
11license = {text = "MIT"}
12authors = [
13 {name = "Your Name", email = "your@email.com"}
14]
15keywords = ["api", "sdk", "your-api"]
16classifiers = [
17 "Development Status :: 5 - Production/Stable",
18 "Intended Audience :: Developers",
19 "License :: OSI Approved :: MIT License",
20 "Programming Language :: Python :: 3",
21 "Programming Language :: Python :: 3.9",
22 "Programming Language :: Python :: 3.10",
23 "Programming Language :: Python :: 3.11",
24]
25
26dependencies = [
27 "requests>=2.31.0",
28 "pydantic>=2.0.0",
29]
30
31[project.optional-dependencies]
32dev = [
33 "pytest>=7.0.0",
34 "black>=23.0.0",
35 "mypy>=1.0.0",
36]
37
38[project.urls]
39Homepage = "https://github.com/your-org/your-sdk"
40Documentation = "https://your-sdk.readthedocs.io"
41Repository = "https://github.com/your-org/your-sdk"
42"Bug Tracker" = "https://github.com/your-org/your-sdk/issues"
43
44[tool.setuptools]
45packages = ["your_sdk"]
46package-dir = {"" = "src"}

Publish your Python SDK to PyPI

To publish your SDK to PyPI, do the following:

  1. Create PyPI account and API token:

    • Register at pypi.org
    • Go to Account Settings > API tokens
    • Create a token with a scope of the entire account or specific project.
  2. Configure the credentials. You can use Twine’s recommended method of storing credentials in ~/.pypirc:

    1[distutils]
    2index-servers =
    3 pypi
    4
    5[pypi]
    6username = __token__
    7password = pypi-YOUR_API_TOKEN_HERE
  3. Build distribution packages:

    $# Install build tools
    $pip install build twine
    $
    $# Build
    $python -m build

    This creates dist/ directory with:

    • your-sdk-1.0.0.tar.gz (source distribution)
    • your_sdk-1.0.0-py3-none-any.whl (wheel distribution)
  4. Check the package:

    $twine check dist/*
  5. Test on TestPyPI first (recommended):

    $# Upload to TestPyPI
    $twine upload --repository testpypi dist/*
    $
    $# Install from TestPyPI to test
    $pip install --index-url https://test.pypi.org/simple/ your-sdk
  6. Publish to PyPI:

    $twine upload dist/*
  7. Verify publication:

    $pip install your-sdk
    $# Or visit: https://pypi.org/project/your-sdk/

Publish updates

  1. Update the version in pyproject.toml:

    1version = "1.0.1"

    Alternatively, if using dynamic versioning, you can set up your pyproject.toml to read the version from your SDK package:

    1[project]
    2dynamic = ["version"]
    3
    4[tool.setuptools.dynamic]
    5version = {attr = "your_sdk.__version__"}
  2. Clean and rebuild:

    $rm -rf dist/
    $python -m build
    $twine upload dist/*

Best practices for publishing Python SDKs

Use the following best practices when publishing your Python SDK to PyPI:

  • Use semantic versioning (MAJOR.MINOR.PATCH).
  • Test on TestPyPI before publishing to PyPI.
  • Include a comprehensive README.md with examples.
  • Add a LICENSE file.
  • Use type hints for better IDE support.
  • Include a py.typed file for PEP 561 compliance.
  • Tag releases in Git: git tag v1.0.0 && git push --tags.
  • Set up GitHub Actions for automated testing and publishing.

The following is an example GitHub Actions workflow (.github/workflows/publish.yml).

1name: Publish Python Package
2
3on:
4 release:
5 types: [published]
6
7jobs:
8 publish:
9 runs-on: ubuntu-latest
10 steps:
11 - uses: actions/checkout@v4
12 - uses: actions/setup-python@v5
13 with:
14 python-version: '3.9'
15 - name: Install dependencies
16 run: |
17 pip install build twine
18 - name: Build package
19 run: python -m build
20 - name: Publish to PyPI
21 env:
22 TWINE_USERNAME: __token__
23 TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
24 run: twine upload dist/*

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.

1sdk = YourSdk(api_key="your-api-key")
2
3# With a custom header name
4sdk = YourSdk(api_key="your-api-key", api_key_header="X-Custom-Key")

To update the credentials after initialization, run the following:

1sdk.set_api_key("new-api-key")
2sdk.set_access_token("new-token")
3sdk.set_basic_auth("new-username", "new-password")
4sdk.set_base_oauth_url("https://new-auth.example.com")

Environment management

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

1from your_sdk import YourSdk, Environment
2
3sdk = YourSdk(
4 base_url=Environment.PRODUCTION,
5 api_key="your-api-key"
6)
7
8# Or custom base URL
9sdk = YourSdk(
10 base_url="https://custom.api.example.com",
11 api_key="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 gracefully in your application.

To handle errors, do the following:

1from your_sdk import YourSdk
2from your_sdk.net.transport.api_error import ApiError
3
4sdk = YourSdk(api_key="your-api-key")
5
6try:
7 user = sdk.users.get_user(user_id="123")
8 print(user)
9except ApiError as e:
10 print(f"API error: {e.message}")
11 print(f"Status code: {e.status}")
12 print(f"Response: {e.response}")
13except Exception as e:
14 print(f"Unexpected error: {e}")

To handle specific error codes, do the following:

1from your_sdk.net.transport.api_error import ApiError
2
3try:
4 sdk.users.delete_user(user_id="123")
5except ApiError as e:
6 if e.status == 404:
7 print("User not found")
8 elif e.status == 403:
9 print("Permission denied")
10 else:
11 print(f"API error: {e.message}")

Timeouts and retries

To set a global timeout, do the following:

1sdk = YourSdk(
2 api_key="your-api-key",
3 timeout=10000 # 10 seconds in milliseconds (default: 60000)
4)

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

1from your_sdk.net import SdkConfig
2
3user = sdk.users.get_user(
4 user_id="123",
5 request_config=SdkConfig(timeout=5000) # 5 seconds for this request
6)

To pass the retry configuration through SdkConfig at SDK, service, or request level, do the following:

1from your_sdk.net import SdkConfig, RetryConfig
2
3sdk = YourSdk(api_key="your-api-key")
4
5# Override retry at the request level
6user = sdk.users.get_user(
7 user_id="123",
8 request_config=SdkConfig(
9 retry=RetryConfig(
10 attempts=3,
11 delay_ms=1000, # 1 second between retries
12 max_delay_ms=30000, # max delay cap
13 backoff_factor=2.0, # exponential backoff multiplier
14 jitter_ms=100, # random jitter
15 status_codes_to_retry=[408, 429, 500, 502, 503, 504],
16 http_methods_to_retry=["GET", "POST", "PUT", "DELETE"]
17 )
18 )
19)

Additional resources

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

  • SDK documentation — Check the documentation/ directory in your SDK for detailed docs on services, models, and code snippets.
  • Example usage — Refer to the examples/ directory for working code samples demonstrating how to use the SDK in different scenarios.
  • Type hints — All methods in the SDK include type hints for better IDE support and code completion.
  • Dependencies — The SDK uses requests for HTTP requests and pydantic for data validation. Make sure to install these dependencies when using the SDK.