Using Generated Code from REST API Client Code Generators
July 6, 2026 ยท View on GitHub
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.
Table of Contents
NSwag
NSwag generates a complete C# HTTP client with all the necessary models and client classes.
Dependencies
The generated code depends on:
- Newtonsoft.Json (v13.0.3 or later)
dotnet add package Newtonsoft.Json
Basic Usage
using 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}");
}
}
}
Dependency Injection
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");
});
}
}
Further Reading
Swagger Codegen CLI
Swagger Codegen CLI generates a traditional REST client with RestSharp for making HTTP requests.
Dependencies
The generated code depends on:
- RestSharp (v105.2.3 or later)
- JsonSubTypes (v1.9.0 or later)
dotnet add package RestSharp
dotnet add package JsonSubTypes
Basic Usage
using 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}");
}
}
}
Configuration Options
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";
Further Reading
OpenAPI Generator
OpenAPI Generator creates a modern REST client with RestSharp and comprehensive support for OpenAPI 3.0+ features.
Dependencies
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.Json
Basic Usage
using 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}");
}
}
}
Advanced Configuration
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";
Advanced Usage: Retry Logic with Polly (Optional)
If you want to add retry logic to your API calls, you can use Polly as an optional dependency.
Install Polly:
dotnet add package Polly
Example 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));
Further Reading
Kiota
Microsoft Kiota generates modern, fluent API clients with strong typing and built-in middleware support.
Dependencies
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.Multipart
Basic Usage
using 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 Authentication
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);
Custom Request Configuration
// 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
});
});
Further Reading
- Kiota Documentation
- Kiota GitHub Repository
- Using Kiota Generated Clients
- Kiota Authentication Providers
Refitter
Refitter generates Refit interfaces from OpenAPI specifications, allowing you to use the declarative HTTP client library.
Dependencies
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.HttpClientFactory
Basic Usage
using 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 with Dependency Injection
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);
}
}
Using IApiResponse for More Control
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}");
}
Advanced Configuration with Polly
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);
}
Further Reading
Additional Resources
Common Patterns
Error Handling
try
{
var result = await client.GetDataAsync();
}
catch (ApiException ex) // NSwag, OpenAPI Generator
{
Console.WriteLine($"API Error: {ex.StatusCode} - {ex.Message}");
}
catch (HttpOperationException ex)
{
Console.WriteLine($"HTTP Error: {ex.Response.StatusCode}");
}
catch (Refit.ApiException ex) // Refitter
{
Console.WriteLine($"Refit Error: {ex.StatusCode}");
}
Cancellation Token Support
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
var result = await client.GetDataAsync(cancellationToken: cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Request was cancelled");
}
Custom HTTP Headers
// 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");
// }
// }
// 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");
});
General Best Practices
- 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
Support
For issues or questions specific to the code generators:
- NSwag: 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.