> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt. For full content including API reference and SDK examples, see https://learning.postman.com/llms-full.txt.

# Use Rust SDKs generated in Postman

This guide provides instructions for using Rust 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 Rust SDKs with type-safe models, service modules for API endpoints, comprehensive error handling with `Result<T, E>`, async/await support using Tokio, and extensive documentation to help you integrate with your API quickly and efficiently. Models leverage serde for JSON serialization/deserialization and provide compile-time type safety with Rust's powerful type system.

## SDK structure

Generated Rust SDKs include the following key components:

* Core client — `src/lib.rs` as the main entry point and `src/client.rs` for the SDK client implementation.
* Service modules — Organized in `src/services/` with individual modules for each service.
* Data models — Type-safe structs and enums in `src/models/` powered by serde.
* HTTP infrastructure — Located in `src/http/` handling configuration, transport, request handling, and authentication.
* Dependencies — Specified in `Cargo.toml` (reqwest, serde, tokio for async support).
  The directory structure includes documentation files, example implementations, and configuration for both development and production environments.

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

<Folder name="your-sdk" defaultOpen>
  <Files>
    <File name="README.md">
      Main documentation
    </File>

    <File name="Cargo.toml">
      Rust package configuration
    </File>

    <File name=".gitignore">
      Git ignore rules
    </File>

    <File name="LICENSE" />
  </Files>

  <Folder name=".devcontainer">
    <File name="devcontainer.json">
      Dev container configuration
    </File>
  </Folder>

  <Folder name="examples">
    <Files>
      <File name="example.rs">
        Basic SDK usage example
      </File>
    </Files>
  </Folder>

  <Folder name="src">
    <Files>
      <File name="lib.rs">
        Library main entry point
      </File>

      <File name="client.rs">
        Main SDK client implementation
      </File>

      <File name="error.rs">
        Error types and handling
      </File>
    </Files>

    <Folder name="http">
      <Files>
        <File name="mod.rs">
          HTTP module declarations
        </File>

        <File name="client.rs">
          HTTP client implementation
        </File>

        <File name="config.rs">
          SDK configuration types
        </File>
      </Files>

      <Folder name="auth">
        <Files>
          <File name="mod.rs">
            Auth dispatch
          </File>

          <File name="api_key.rs">
            API key authentication
          </File>

          <File name="bearer.rs">
            Bearer token authentication
          </File>

          <File name="basic.rs">
            Basic authentication
          </File>
        </Files>
      </Folder>
    </Folder>

    <Folder name="services">
      <Files>
        <File name="mod.rs">
          Service module declarations
        </File>

        <File name="[service_name].rs">
          Individual service implementations
        </File>
      </Files>
    </Folder>

    <Folder name="models">
      <Files>
        <File name="mod.rs">
          Model module declarations
        </File>

        <File name="[model_name].rs">
          Individual model definitions
        </File>
      </Files>
    </Folder>
  </Folder>
</Folder>

## Type safety with serde

Generated models leverage serde for serialization and Rust's type system for compile-time safety. All API interactions are validated at compile time, eliminating runtime type errors.

### Model serialization

Models automatically serialize to and from JSON using serde. The SDK handles field renaming, optional fields, and nested structures:

```rust
use your_sdk::models::Pet;
use serde_json;

// Create a model instance
let pet = Pet {
    name: "Fluffy".to_string(),
    status: "available".to_string(),
    id: Some(1),
    category: None,
};

// Serialize to JSON
let json = serde_json::to_string(&pet)?;
// {"name":"Fluffy","status":"available","id":1}

// Deserialize from JSON
let pet: Pet = serde_json::from_str(&json)?;
```

### Optional and nullable fields

The SDK distinguishes between `Option<T>` fields (can be omitted) and fields that can be explicitly null using custom serde annotations:

```rust
use your_sdk::models::UpdateContainerGroup;

// Only set fields are included in API requests
let update = UpdateContainerGroup {
    replicas: Some(2),
    country_codes: Some(vec!["us".to_string(), "eu".to_string()]),
    liveness_probe: None, // This field is omitted from the request
    display_name: Some("Updated Container".to_string()),
};
```

### Error handling

The SDK uses Rust's `Result<T, E>` type for comprehensive error handling. All API calls return a `Result` with detailed error information.

## Example usage

Each generated SDK includes an `examples/` directory with working projects demonstrating various SDK usage patterns.

The examples include the following features:

* Async usage patterns with Tokio
* SDK configuration with different authentication methods
* Type-safe API calls with full IntelliSense support
* Comprehensive error handling with custom error types
* Best practices for production usage

<Tabs>
  <Tab title="Location">
    `examples/example.rs`
  </Tab>

  <Tab title="Run the example">
    ```bash
    cd path/to/your-sdk
    cargo run --example example
    ```
  </Tab>

  <Tab title="Example code structure">
    ```rust
    use your_sdk::{YourSdkClient, YourSdkConfig};
    use your_sdk::http::Environment;
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let config = YourSdkConfig::builder()
            .access_token("your-api-key")
            .environment(Environment::Production)
            .timeout_ms(30000)
            .build()
            .expect("Failed to build configuration");
        let client = YourSdkClient::new(config)?;
        match client.pets().list_pets(None).await {
            Ok(pets) => {
                println!("Pets: {:?}", pets);
            }
            Err(error) => {
                eprintln!("Error: {}", error);
            }
        }
        Ok(())
    }
    ```
  </Tab>

  <Tab title="Async example">
    ```rust
    use your_sdk::{YourSdkClient, YourSdkConfig};
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let config = YourSdkConfig::builder()
            .access_token("your-bearer-token")
            .build()
            .expect("Failed to build configuration");
        let client = YourSdkClient::new(config)?;
        // Multiple concurrent requests
        let (pet1, pet2) = tokio::try_join!(
            client.pets().get_pet_by_id("123".to_string()),
            client.pets().get_pet_by_id("456".to_string())
        )?;
        println!("Pet 1: {:?}", pet1);
        println!("Pet 2: {:?}", pet2);
        Ok(())
    }
    ```
  </Tab>
</Tabs>

## Install the Rust SDK

You can add the generated SDK to your Rust project using Cargo, either from a published crate or as a local dependency.

### Install using Cargo

To add the SDK as a dependency from crates.io, add it to your `Cargo.toml`:

```toml
[dependencies]
your-sdk = "1.0.0"
tokio = { version = "1.0", features = ["full"] }
```

Then use it in your code:

### Install from a local path

To use the SDK from a local directory, add it as a path dependency in your `Cargo.toml`:

```toml
[dependencies]
your-sdk = { path = "../path/to/your-sdk" }
tokio = { version = "1.0", features = ["full"] }
```

### Install from Git repository

To install from a Git repository, add it as a Git dependency:

```toml
[dependencies]
your-sdk = { git = "https://github.com/your-org/your-sdk", branch = "main" }
tokio = { version = "1.0", features = ["full"] }
```

For a specific version or tag:

```toml
[dependencies]
your-sdk = { git = "https://github.com/your-org/your-sdk", tag = "v1.0.0" }
```

## Publish to crates.io

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

### Prerequisites

To publish your SDK to crates.io, you need the following:

* A crates.io account (create at [crates.io](https://crates.io/))
* Cargo installed with Rust toolchain
* API token from crates.io

### Configure Cargo.toml

Ensure your SDK's `Cargo.toml` is properly configured for publication:

### Publish your Rust SDK to crates.io

To publish your SDK to crates.io, do the following:

1. Create crates.io account and get API token:

   * Register at [crates.io](https://crates.io/)
   * Go to Account Settings > API Tokens
   * Create a new token with appropriate permissions

2. Login to crates.io using Cargo:

   ```bash
   cargo login <your-api-token>
   ```

3. Verify your package builds correctly:

   ```bash
   # Check for common issues
   cargo check

   # Run tests
   cargo test

   # Build documentation
   cargo doc

   # Verify package contents
   cargo package --list
   ```

4. Test the package build:

   ```bash
   # This creates a .crate file without publishing
   cargo package
   ```

5. Publish to crates.io:

   ```bash
   cargo publish
   ```

6. Verify publication:

   ```bash
   # In a separate test project, add your published crate as a dependency
   cargo new verify-your-sdk
   cd verify-your-sdk
   cargo add your-sdk

   # Build the project to verify the crate resolves and compiles
   cargo check

   # Or visit: https://crates.io/crates/your-sdk
   ```

   Use `cargo install your-sdk` only if your crate also publishes a binary target.

### Publish updates

To publish a new version of your SDK:

1. Update the version in `Cargo.toml`:

   ```toml
   version = "1.0.1"
   ```

2. Update dependencies if needed and test:

   ```bash
   cargo update
   cargo test
   ```

3. Publish the new version:

   ```bash
   cargo publish
   ```

### Best practices for publishing Rust SDKs

Use the following best practices when publishing your Rust SDK to crates.io:

* Follow semantic versioning (`MAJOR.MINOR.PATCH`).
* Include comprehensive documentation with `cargo doc`.
* Use appropriate keywords and categories for discoverability.
* Test your package thoroughly with `cargo test`.
* Consider using features for optional functionality.
* Keep your API surface minimal and follow Rust naming conventions.
* Use `#[non_exhaustive]` on enums and structs that might grow.
* Provide good error messages and use `thiserror` for error handling.

### Advanced configuration

For production SDKs, consider these additional configurations:

#### Custom feature flags

```toml
[features]
default = ["reqwest-default"]
reqwest-default = ["reqwest/default-tls"]
reqwest-rustls = ["reqwest/rustls-tls"]
blocking = ["reqwest/blocking"]
```

#### Documentation settings

```toml
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
```

This ensures that `docs.rs` builds your documentation with all features enabled and proper conditional compilation attributes.