This guide explains how to use the code generated by the various code generators supported by this tool. Each generator produces code with different dependencies and usage patterns.
NSwag generates a complete C# HTTP client with all the necessary models and client classes.
The generated code depends on:
- Newtonsoft.Json (v13.0.3 or later)
dotnet add package Newtonsoft.Jsonusing System;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
// Create HttpClient with base address
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://petstore.swagger.io/v2")
};
// Create the client instance
var client = new SwaggerClient(httpClient);
try
{
// Call API methods
var pet = await client.GetPetByIdAsync(1);
Console.WriteLine($"Pet Name: {pet.Name}");
// Get all pets by status
var availablePets = await client.FindPetsByStatusAsync(
new[] { Anonymous.Available });
Console.WriteLine($"Available Pets: {availablePets.Count}");
}
catch (ApiException ex)
{
Console.WriteLine($"API Error: {ex.StatusCode} - {ex.Message}");
}
}
}using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<ISwaggerClient, SwaggerClient>(client =>
{
client.BaseAddress = new Uri("https://petstore.swagger.io/v2");
});
}
}AutoRest v2 generates clients for OpenAPI v2 specifications with comprehensive model and operation support.
The generated code depends on:
- Microsoft.Rest.ClientRuntime (v2.3.24 or later)
- Newtonsoft.Json (v13.0.3 or later)
dotnet add package Microsoft.Rest.ClientRuntime
dotnet add package Newtonsoft.Jsonusing System;
using System.Threading.Tasks;
using Microsoft.Rest;
public class Program
{
public static async Task Main(string[] args)
{
// Create credentials (if required)
var credentials = new TokenCredentials("your-api-key");
// Create client with base URI
var client = new SwaggerPetstoreClient(new Uri("https://petstore.swagger.io/v2"))
{
Credentials = credentials
};
try
{
// Call API operations
var pet = await client.GetPetByIdAsync(1);
Console.WriteLine($"Pet Name: {pet.Name}");
// List pets by status
var pets = await client.FindPetsByStatusAsync(new[] { "available" });
Console.WriteLine($"Found {pets.Count} pets");
}
catch (HttpOperationException ex)
{
Console.WriteLine($"Request failed: {ex.Response.StatusCode}");
Console.WriteLine($"Response: {ex.Response.Content}");
}
}
}using Microsoft.Rest;
// Token-based authentication (most common)
var tokenCreds = new TokenCredentials("your-bearer-token");
var client = new SwaggerPetstoreClient(new Uri("https://petstore.swagger.io/v2"))
{
Credentials = tokenCreds
};
// Custom authentication header
var client2 = new SwaggerPetstoreClient(new Uri("https://api.example.com"));
client2.HttpClient.DefaultRequestHeaders.Add("X-API-Key", "your-api-key");AutoRest v3 generates clients for OpenAPI v3 specifications with improved support for modern OpenAPI features.
The generated code depends on:
- Azure.Core (v1.0.0 or later)
- System.Text.Json (v4.7.2 or later)
dotnet add package Azure.Core
dotnet add package System.Text.Jsonusing System;
using System.Threading.Tasks;
using Azure;
public class Program
{
public static async Task Main(string[] args)
{
// Create client with credentials
var credentials = new TokenCredentials("your-api-key");
var client = new GeneratedCodeClient(credentials)
{
BaseUri = new Uri("https://api.example.com")
};
try
{
// Use generated operations
var result = await client.Operations.GetResourceAsync("resource-id");
Console.WriteLine($"Resource: {result.Name}");
// Create new resource
var newResource = new Resource
{
Name = "New Resource",
Description = "Created via API"
};
var created = await client.Operations.CreateResourceAsync(newResource);
Console.WriteLine($"Created: {created.Id}");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"API Error: {ex.Status} - {ex.Message}");
}
}
}using System.Net.Http;
// Create custom HttpClient with handlers
var httpClient = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = System.Net.DecompressionMethods.GZip
});
// Create client with custom HttpClient
var client = new GeneratedCodeClient(
credentials,
httpClient,
disposeHttpClient: false);Swagger Codegen CLI generates a traditional REST client with RestSharp for making HTTP requests.
The generated code depends on:
- RestSharp (v105.2.3 or later)
- JsonSubTypes (v1.9.0 or later)
dotnet add package RestSharp
dotnet add package JsonSubTypesusing System;
using System.Collections.Generic;
using System.Threading.Tasks;
using IO.Swagger.Api;
using IO.Swagger.Client;
using IO.Swagger.Model;
public class Program
{
public static async Task Main(string[] args)
{
// Configure API client
Configuration.Default.BasePath = "https://petstore.swagger.io/v2";
Configuration.Default.ApiKey.Add("api_key", "your-api-key");
// Create API instance
var petApi = new PetApi();
try
{
// Get a pet by ID
var pet = await petApi.GetPetByIdAsync(1);
Console.WriteLine($"Pet: {pet.Name} - {pet.Status}");
// Add a new pet
var newPet = new Pet
{
Name = "Fluffy",
Status = Pet.StatusEnum.Available,
PhotoUrls = new List<string> { "http://example.com/photo.jpg" }
};
await petApi.AddPetAsync(newPet);
Console.WriteLine("Pet added successfully");
}
catch (ApiException ex)
{
Console.WriteLine($"API Error: {ex.ErrorCode} - {ex.Message}");
}
}
}using IO.Swagger.Client;
// Set base path
Configuration.Default.BasePath = "https://api.example.com";
// Add API key
Configuration.Default.ApiKey.Add("Authorization", "Bearer your-token");
// Set timeout
Configuration.Default.Timeout = 30000; // 30 seconds
// Configure user agent
Configuration.Default.UserAgent = "MyApp/1.0";OpenAPI Generator creates a modern REST client with RestSharp and comprehensive support for OpenAPI 3.0+ features.
The generated code depends on:
- RestSharp (v112.0.0 or later)
- JsonSubTypes (v2.0.1 or later)
- Newtonsoft.Json (v13.0.3 or later)
dotnet add package RestSharp
dotnet add package JsonSubTypes
dotnet add package Newtonsoft.Jsonusing System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Client;
using Org.OpenAPITools.Model;
public class Program
{
public static async Task Main(string[] args)
{
// Configure the API client
var config = new Configuration
{
BasePath = "https://petstore.swagger.io/v2"
};
// Add authentication if needed
config.ApiKey.Add("api_key", "your-api-key");
// Create API instance
var petApi = new PetApi(config);
try
{
// Fetch a pet
var pet = await petApi.GetPetByIdAsync(1);
Console.WriteLine($"Pet: {pet.Name}");
// Update a pet
pet.Status = Pet.StatusEnum.Sold;
await petApi.UpdatePetAsync(pet);
Console.WriteLine("Pet updated");
// Find pets by status
var availablePets = await petApi.FindPetsByStatusAsync(
new List<string> { "available" });
Console.WriteLine($"Found {availablePets.Count} available pets");
}
catch (ApiException ex)
{
Console.WriteLine($"Error: {ex.ErrorCode} - {ex.Message}");
Console.WriteLine($"Response: {ex.ErrorContent}");
}
}
}using Org.OpenAPITools.Client;
var config = new Configuration
{
BasePath = "https://api.example.com",
Timeout = 30000,
UserAgent = "MyApp/1.0"
};
// Configure OAuth2
config.AccessToken = "your-oauth-token";If you want to add retry logic to your API calls, you can use Polly as an optional dependency.
Install Polly:
dotnet add package PollyExample usage:
using Polly;
using Polly.Extensions.Http;
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Client;
// Configure retry policy with Polly
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
var config = new Configuration
{
BasePath = "https://api.example.com"
};
var petApi = new PetApi(config);
// Execute API call with retry policy
var pet = await retryPolicy.ExecuteAsync(() => petApi.GetPetByIdAsync(1));Microsoft Kiota generates modern, fluent API clients with strong typing and built-in middleware support.
The generated code depends on:
- Microsoft.Kiota.Abstractions
- Microsoft.Kiota.Http.HttpClientLibrary
- Microsoft.Kiota.Serialization.Form
- Microsoft.Kiota.Serialization.Text
- Microsoft.Kiota.Serialization.Json
- Microsoft.Kiota.Serialization.Multipart
- Microsoft.Kiota.Authentication.Azure (optional)
- Azure.Identity (optional)
dotnet add package Microsoft.Kiota.Abstractions
dotnet add package Microsoft.Kiota.Http.HttpClientLibrary
dotnet add package Microsoft.Kiota.Serialization.Form
dotnet add package Microsoft.Kiota.Serialization.Text
dotnet add package Microsoft.Kiota.Serialization.Json
dotnet add package Microsoft.Kiota.Serialization.Multipartusing System;
using System.Threading.Tasks;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary;
public class Program
{
public static async Task Main(string[] args)
{
// Create authentication provider (anonymous for public APIs)
var authProvider = new AnonymousAuthenticationProvider();
// Create HTTP adapter
var adapter = new HttpClientRequestAdapter(authProvider)
{
BaseUrl = "https://petstore.swagger.io/v2"
};
// Create the API client
var client = new ApiClient(adapter);
try
{
// Use fluent API to make requests
var pet = await client.Pet.ById(1).GetAsync();
Console.WriteLine($"Pet: {pet.Name}");
// Query with parameters
var pets = await client.Pet.FindByStatus.GetAsync(config =>
{
config.QueryParameters.Status = new[] { "available" };
});
Console.WriteLine($"Found {pets.Count} pets");
// Create a new resource
var newPet = new Pet
{
Name = "Buddy",
Status = "available"
};
await client.Pet.PostAsync(newPet);
Console.WriteLine("Pet created");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}using Azure.Identity;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Authentication.Azure;
// Use Azure AD authentication
var credential = new DefaultAzureCredential();
var authProvider = new AzureIdentityAuthenticationProvider(credential);
var adapter = new HttpClientRequestAdapter(authProvider)
{
BaseUrl = "https://api.example.com"
};
var client = new ApiClient(adapter);// Configure individual requests
var result = await client.Resource.GetAsync(config =>
{
config.Headers.Add("Custom-Header", "value");
config.QueryParameters.Filter = "status eq 'active'";
config.Options.Add(new ResponseHandlerOption
{
ResponseHandler = customHandler
});
});- Kiota Documentation
- Kiota GitHub Repository
- Using Kiota Generated Clients
- Kiota Authentication Providers
Refitter generates Refit interfaces from OpenAPI specifications, allowing you to use the declarative HTTP client library.
The generated code depends on:
- Refit (v8.0.0 or later)
- Refit.HttpClientFactory (optional, for DI support)
dotnet add package Refit
dotnet add package Refit.HttpClientFactoryusing System;
using System.Threading.Tasks;
using Refit;
public class Program
{
public static async Task Main(string[] args)
{
// Create Refit client
var client = RestService.For<ISwaggerPetstore>(
"https://petstore.swagger.io/v2");
try
{
// Call API methods
var pet = await client.GetPetById(1);
Console.WriteLine($"Pet: {pet.Name}");
// Get pets by status
var pets = await client.FindPetsByStatus("available");
Console.WriteLine($"Found {pets.Count} pets");
// Create a new pet
var newPet = new Pet
{
Name = "Max",
Status = "available",
PhotoUrls = new[] { "http://example.com/photo.jpg" }
};
await client.AddPet(newPet);
Console.WriteLine("Pet added");
}
catch (ApiException ex)
{
Console.WriteLine($"API Error: {ex.StatusCode}");
Console.WriteLine($"Content: {ex.Content}");
}
}
}using Microsoft.Extensions.DependencyInjection;
using Refit;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Basic registration
services.AddRefitClient<ISwaggerPetstore>()
.ConfigureHttpClient(c =>
c.BaseAddress = new Uri("https://petstore.swagger.io/v2"));
}
}
// Alternative: With authentication
public class Startup2
{
public void ConfigureServices(IServiceCollection services)
{
services.AddRefitClient<ISwaggerPetstore>()
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri("https://api.example.com");
c.DefaultRequestHeaders.Add("Authorization", "Bearer your-token");
});
}
}
// Use in your services
public class PetService
{
private readonly ISwaggerPetstore _api;
public PetService(ISwaggerPetstore api)
{
_api = api;
}
public async Task<Pet> GetPetAsync(long id)
{
return await _api.GetPetById(id);
}
}If Refitter is configured to return IApiResponse<T>, you get access to headers and status codes:
using System.Linq;
using Refit;
var response = await client.GetPetById(1);
if (response.IsSuccessStatusCode)
{
var pet = response.Content;
Console.WriteLine($"Pet: {pet.Name}");
// Access response headers
var rateLimit = response.Headers.GetValues("X-Rate-Limit").FirstOrDefault();
Console.WriteLine($"Rate Limit: {rateLimit}");
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
var error = response.Error;
Console.WriteLine($"Error Content: {error?.Content}");
}using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.Extensions.Http;
using Refit;
public void ConfigureServices(IServiceCollection services)
{
// Configure retry policy
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
services.AddRefitClient<ISwaggerPetstore>()
.ConfigureHttpClient(c =>
c.BaseAddress = new Uri("https://petstore.swagger.io/v2"))
.AddPolicyHandler(retryPolicy);
}try
{
var result = await client.GetDataAsync();
}
catch (ApiException ex) // NSwag, OpenAPI Generator
{
Console.WriteLine($"API Error: {ex.StatusCode} - {ex.Message}");
}
catch (HttpOperationException ex) // AutoRest
{
Console.WriteLine($"HTTP Error: {ex.Response.StatusCode}");
}
catch (Refit.ApiException ex) // Refitter
{
Console.WriteLine($"Refit Error: {ex.StatusCode}");
}var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
var result = await client.GetDataAsync(cancellationToken: cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Request was cancelled");
}// NSwag - Option 1: Add header to all requests via HttpClient
httpClient.DefaultRequestHeaders.Add("Custom-Header", "value");
var client = new SwaggerClient(httpClient);
// NSwag - Option 2: Override PrepareRequest partial method for per-request headers
// Add this to a partial class in your project:
// partial class SwaggerClient
// {
// partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url)
// {
// request.Headers.Add("Custom-Header", "value");
// }
// }
// AutoRest
client.HttpClient.DefaultRequestHeaders.Add("Custom-Header", "value");
// OpenAPI Generator
config.DefaultHeaders.Add("Custom-Header", "value");
// Kiota
await client.Resource.GetAsync(config =>
{
config.Headers.Add("Custom-Header", "value");
});
// Refitter with Refit
services.AddRefitClient<IApi>()
.ConfigureHttpClient(c =>
{
c.DefaultRequestHeaders.Add("Custom-Header", "value");
});- Use Dependency Injection: Register clients with DI containers for better testability
- Handle Errors Gracefully: Always catch and handle API exceptions appropriately
- Use Cancellation Tokens: Support cancellation for long-running operations
- Configure Timeouts: Set appropriate timeouts to prevent hanging requests
- Implement Retry Logic: Use Polly or built-in retry mechanisms for resilience
- Secure API Keys: Store API keys and secrets securely, never in code
- Log API Calls: Implement logging for debugging and monitoring
For issues or questions specific to the code generators:
- NSwag: GitHub Issues
- AutoRest: GitHub Issues
- Swagger Codegen: GitHub Issues
- OpenAPI Generator: GitHub Issues
- Kiota: GitHub Issues
- Refitter: GitHub Issues
For issues with this tool itself, please visit the REST API Client Code Generator Issues.