*** title: Use Python SDKs generated in Postman updated: 2026-02-20T00:00:00.000Z max-toc-depth: 2 ---------------- 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: Main documentation PyPI-specific readme Python package configuration Git ignore rules Installation script (Unix) Installation script (Windows) Dev container configuration Package initialization Synchronous SDK client Async SDK client Sync service classes Async service variants SdkConfig and RetryConfig ApiError exception class Additional handlers Auth header implementations Environment configuration Example usage Example installation script Service documentation Model documentation Code snippets ## 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: ```python from pydantic import ValidationError from your_sdk.models import Pet # Valid usage pet = Pet(name="Fluffy", status="available") # Invalid usage — raises ValidationError try: pet = Pet(name=123, status="available") except ValidationError as e: print(e) # 1 validation error for Pet # name # 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: ```python from your_sdk.models import UpdateContainerGroup # Only `replicas` and `country_codes` are sent in the request body. # `liveness_probe` is sent as null because it was explicitly set to None. # Unset fields like `display_name` are omitted entirely. container = UpdateContainerGroup( replicas=2, country_codes=["us"], liveness_probe=None, # sent as null ) ``` ### 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: ```python pet = Pet(name="Fluffy", status="available") # Serializes using the API field names (aliases) payload = pet.model_dump_original() # {"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: ```python pet = Pet(name="Fluffy", status="available", undocumented_field="value") pet._kwargs # {"undocumented_field": "value"} pet.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` ```bash cd examples python sample.py ``` ```python from your_sdk import YourSdk # Initialize the SDK sdk = YourSdk( api_key="your-api-key", base_url="https://api.example.com" ) try: # Call an API endpoint user = sdk.users.get_user(user_id="123") print(f"User: {user}") except Exception as error: print(f"Error: {error}") ``` ```python import asyncio from your_sdk import AsyncSdk async def main(): sdk = AsyncSdk(api_key="your-api-key") user = await sdk.users.get_user(user_id="123") print(f"User: {user}") asyncio.run(main()) ``` ## 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. ```bash cd path/to/your-sdk pip install -e . ``` 2. Use the SDK in your code. ```python from your_sdk import YourSdk sdk = 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: ```bash 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: ```bash export PYTHONPATH="${PYTHONPATH}:/path/to/your-sdk/src" ``` 2. Use the SDK in your code: ```python from your_sdk import YourSdk ``` ### Import using Poetry To import the SDK using Poetry, add it as a dependency with a local path: ```bash poetry add ../path/to/your-sdk ``` To import the SDK in `pyproject.toml`, add the following line to the `[tool.poetry.dependencies]` section: ```toml [tool.poetry.dependencies] your-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](https://pypi.org/account/register/)) * Twine installed: `pip install twine` ### Configure pyproject.toml Ensure your SDK's `pyproject.toml` is properly configured: ```toml [build-system] requires = ["setuptools>=61.0", "wheel"] build-backend = "setuptools.build_meta" [project] name = "your-sdk" version = "1.0.0" description = "SDK for Your API" readme = "README.md" requires-python = ">=3.9" license = {text = "MIT"} authors = [ {name = "Your Name", email = "your@email.com"} ] keywords = ["api", "sdk", "your-api"] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ] dependencies = [ "requests>=2.31.0", "pydantic>=2.0.0", ] [project.optional-dependencies] dev = [ "pytest>=7.0.0", "black>=23.0.0", "mypy>=1.0.0", ] [project.urls] Homepage = "https://github.com/your-org/your-sdk" Documentation = "https://your-sdk.readthedocs.io" Repository = "https://github.com/your-org/your-sdk" "Bug Tracker" = "https://github.com/your-org/your-sdk/issues" [tool.setuptools] packages = ["your_sdk"] package-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](https://pypi.org/account/register/) * 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`: ```ini [distutils] index-servers = pypi [pypi] username = __token__ password = pypi-YOUR_API_TOKEN_HERE ``` 3. Build distribution packages: ```bash # 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: ```bash twine check dist/* ``` 5. Test on TestPyPI first (recommended): ```bash # 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: ```bash twine upload dist/* ``` 7. Verify publication: ```bash pip install your-sdk # Or visit: https://pypi.org/project/your-sdk/ ``` ### Publish updates 1. Update the version in `pyproject.toml`: ```toml version = "1.0.1" ``` Alternatively, if using dynamic versioning, you can set up your `pyproject.toml` to read the version from your SDK package: ```toml [project] dynamic = ["version"] [tool.setuptools.dynamic] version = {attr = "your_sdk.__version__"} ``` 2. Clean and rebuild: ```bash 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`). ```yaml name: Publish Python Package on: release: types: [published] jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.9' - name: Install dependencies run: | pip install build twine - name: Build package run: python -m build - name: Publish to PyPI env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} 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. ```python sdk = YourSdk(api_key="your-api-key") # With a custom header name sdk = YourSdk(api_key="your-api-key", api_key_header="X-Custom-Key") ``` ```python sdk = YourSdk(access_token="your-bearer-token") ``` ```python sdk = YourSdk( username="your-username", password="your-password" ) ``` ```python sdk = YourSdk( client_id="your-client-id", client_secret="your-client-secret", base_oauth_url="https://auth.example.com" ) # SDK automatically handles token refresh user = sdk.users.get_user(user_id="123") ``` ```python sdk = YourSdk(access_token="your-access-token") ``` To update the credentials after initialization, run the following: ```python sdk.set_api_key("new-api-key") sdk.set_access_token("new-token") sdk.set_basic_auth("new-username", "new-password") sdk.set_base_oauth_url("https://new-auth.example.com") ``` ### Environment management The SDK supports multiple environments (for example, production, staging) with different base URLs. ```python from your_sdk import YourSdk, Environment sdk = YourSdk( base_url=Environment.PRODUCTION, api_key="your-api-key" ) # Or custom base URL sdk = YourSdk( base_url="https://custom.api.example.com", api_key="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 gracefully in your application. To handle errors, do the following: ```python from your_sdk import YourSdk from your_sdk.net.transport.api_error import ApiError sdk = YourSdk(api_key="your-api-key") try: user = sdk.users.get_user(user_id="123") print(user) except ApiError as e: print(f"API error: {e.message}") print(f"Status code: {e.status}") print(f"Response: {e.response}") except Exception as e: print(f"Unexpected error: {e}") ``` To handle specific error codes, do the following: ```python from your_sdk.net.transport.api_error import ApiError try: sdk.users.delete_user(user_id="123") except ApiError as e: if e.status == 404: print("User not found") elif e.status == 403: print("Permission denied") else: print(f"API error: {e.message}") ``` ### Timeouts and retries To set a global timeout, do the following: ```python sdk = YourSdk( api_key="your-api-key", timeout=10000 # 10 seconds in milliseconds (default: 60000) ) ``` To set a per-request timeout, do the following: ```python from your_sdk.net import SdkConfig user = sdk.users.get_user( user_id="123", request_config=SdkConfig(timeout=5000) # 5 seconds for this request ) ``` To pass the retry configuration through `SdkConfig` at SDK, service, or request level, do the following: ```python from your_sdk.net import SdkConfig, RetryConfig sdk = YourSdk(api_key="your-api-key") # Override retry at the request level user = sdk.users.get_user( user_id="123", request_config=SdkConfig( retry=RetryConfig( attempts=3, delay_ms=1000, # 1 second between retries max_delay_ms=30000, # max delay cap backoff_factor=2.0, # exponential backoff multiplier jitter_ms=100, # random jitter status_codes_to_retry=[408, 429, 500, 502, 503, 504], http_methods_to_retry=["GET", "POST", "PUT", "DELETE"] ) ) ) ``` ## 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.