Use C# SDKs generated in Postman
Use C# SDKs generated in Postman
This guide provides instructions for using C# SDKs generated by the Postman SDK Generator. It covers how to install the SDK into your project, run example code, and best practices for using the SDK effectively in your applications.
SDK structure
The C# SDK includes the following key files:
[SdkName]Client.cs— The main SDK client that implementsIDisposableand provides access to all services.Services/[ServiceName]Service.cs— Service classes with async API methods.Models/[ModelName].cs— Data models (records or classes withSystem.Text.Jsonserialization).Config/[SdkName]Config.cs— SDK-level configuration record (environment, auth, timeout).Config/RequestConfig.cs— Per-request configuration overrides.Config/RetryConfig.cs— Retry policy configuration.Config/ApiKeyAuthConfig.cs— API key authentication configuration (generated when applicable).Config/BasicAuthConfig.cs— Basic authentication configuration (generated when applicable).Http/Environment.cs— Environment class with static named environment properties.Http/Exceptions/ApiException.cs— Base exception class for all API errors.Http/Exceptions/[ModelName]Exception.cs— Typed exception classes for spec-defined error models.Models/Optional.cs— AnOptional<T>wrapper for optional fields.examples/Program.cs— Runnable example demonstrating SDK usage.[SdkName].csproj— .NET project and NuGet package configuration.
The following is an example of the typical structure of a generated C# SDK:
Example usage
Each generated SDK includes an examples/Program.cs file demonstrating SDK initialization, making an API call, and basic error handling.
The example includes the following features:
- SDK configuration
- Type-safe API calls
- Error handling with custom exceptions
Location
Run the example
Example code structure
examples/Program.cs
Install the C# SDK
You can install the generated C# SDK into your project using NuGet or by referencing it directly from the filesystem.
Install using NuGet
To install the SDK from NuGet, run:
Then use it in your code:
Install from a local path
If the SDK isn’t published to NuGet yet, you can reference it directly from the filesystem using ProjectReference in your .csproj file.
Alternatively, build the SDK as a NuGet package and add it to a local feed:
Publish to NuGet
Publishing your SDK to NuGet.org makes it available to any .NET developer using dotnet add package.
Prerequisites
To publish your SDK to NuGet, you need the following:
- A NuGet.org account.
- An API key from your NuGet account settings.
Configure the project file
The generated [SdkName].csproj already includes the metadata required for publishing. Review and update the following fields before publishing.
Publish your C# SDK to NuGet
To publish your SDK to NuGet, do the following:
-
Build and pack the SDK.
-
Publish to NuGet.
-
Verify the publication at
https://www.nuget.org/packages/YourSdk. Packages are typically indexed within 15–30 minutes.
Publish updates
To publish updates to your SDK, run the following:
Best practices for publishing C# SDKs
Use the following best practices when publishing your C# SDK to NuGet:
- Use semantic versioning.
- Generate and include XML documentation by setting
<GenerateDocumentationFile>true</GenerateDocumentationFile>in your.csprojfile. - Tag releases in Git.
- Include a
.snupkgsymbols package for debugging support by adding<IncludeSymbols>true</IncludeSymbols>and<SymbolPackageFormat>snupkg</SymbolPackageFormat>.
Advanced usage
The following sections cover advanced usage topics for the generated C# SDK, including authentication, asynchronous calls, environment management, hierarchical configuration, error handling, and timeouts and retries.
Authentication
The SDK supports various authentication methods. Configure authentication when creating the configuration record passed to the SDK client constructor.
The SDK includes authentication support based on the security schemes defined in your API specification. The following examples show the possible authentication methods.
API Key
Bearer Token
Basic Auth
OAuth 2.0
Each generated auth property is only present in the configuration when the corresponding auth type is defined in the specification.
Asynchronous calls and cancellation
All service methods are asynchronous and follow the standard .NET async/await pattern. Every method accepts an optional CancellationToken as its last parameter, allowing you to cancel in-flight requests.
Environment management
The SDK generates an Environment class with static properties for each named server defined in your API specification.
Available environments are defined in Http/Environment.cs as static properties. If your API specification includes servers with names like “production”, “development”, or “staging”, those are generated as properties on the Environment class for easy reference.
Hierarchical configuration
C# supports four levels of configuration. Each level overrides the previous, with request-level being the most specific.
RequestConfig is a C# record with optional properties. Only the values you provide override the inherited configuration; omitted properties fall through to the next level.
Error handling
Service methods throw exceptions on API errors. The base exception class is ApiException, which wraps the underlying HttpResponseMessage. Catch ApiException for general error handling.
To handle specific status codes, run the following:
When the API specification defines typed error response models (for example, a NotFoundError schema on a 404 response), the SDK generates a corresponding typed exception class that extends ApiException. Access the deserialized error model through the named property on the exception:
Timeouts and retries
To set a global timeout, run the following:
The timeout can also be set at construction time through RequestConfig on the config:
To configure retries, pass a RetryConfig record at construction time or per-request:
The following table shows the default retry configuration values used by the SDK if no RetryConfig is provided:
Validation
The SDK validates required parameters before sending the request. If a required argument is null, the service method throws an ArgumentNullException immediately, without making an HTTP call.
No manual validation calls are needed. Validation is built into every service method.
Optional and nullable field handling
The SDK uses two patterns to represent optional and nullable fields, providing a clear distinction between undefined, null, and present values. This is important when building request models, as omitting an optional field versus explicitly setting it to null produces different JSON payloads.
- Required non-nullable fields are plain C# types and must always be provided and can’t be
null. - Required nullable fields use C# nullable types (
string?,long?) and must be provided, but may benull. - Optional fields use the
Optional<T>struct. This wrapper distinguishes between “not provided” (field omitted from JSON) and “provided with a value” (field included in JSON, even ifnullforOptional<T?>).
The following examples show the full range of field combinations:
When reading responses, Optional<T> fields deserialized from the server response will have IsProvided = true if the field was present in the JSON (even if null for nullable types), and IsProvided = false if the field was absent.
Resource cleanup
The SDK client implements IDisposable and manages the lifecycle of its internal HttpClient. Always dispose of the client when you are finished using it to release HTTP resources.
Additional resources
Consider the following resources for using and customizing your C# SDK:
- SDK documentation — Check the
documentation/directory inside your SDK for per-service and per-model reference pages. - XML documentation — Enable
<GenerateDocumentationFile>true</GenerateDocumentationFile>in the.csprojfile and browse IntelliSense docs directly in your IDE. - NuGet Gallery — Once published, your SDK’s page is available at
https://www.nuget.org/packages/YourSdk. - Example usage — See
examples/Program.csfor a runnable demonstration of the SDK. - Dependencies — The SDK targets .NET 6 or later and uses
System.Text.Jsonfor serialization and Polly for retry resilience.