Skip to content

Latest commit

 

History

History
863 lines (677 loc) · 23.6 KB

File metadata and controls

863 lines (677 loc) · 23.6 KB

Using Generated Code from REST API Client Code Generators

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:

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


AutoRest v2

⚠️ DEPRECATED: AutoRest is deprecated by Microsoft and will be retired on July 1, 2026. Please migrate to NSwag, Refitter, or Kiota. See the AutoRest Migration Guide for details.

AutoRest v2 generates clients for OpenAPI v2 specifications with comprehensive model and operation support.

Dependencies

The generated code depends on:

dotnet add package Microsoft.Rest.ClientRuntime
dotnet add package Newtonsoft.Json

Basic Usage

using 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 with Service Credentials

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");

Further Reading


AutoRest v3

⚠️ DEPRECATED: AutoRest is deprecated by Microsoft and will be retired on July 1, 2026. Please migrate to NSwag, Refitter, or Kiota. See the AutoRest Migration Guide for details.

AutoRest v3 generates clients for OpenAPI v3 specifications with improved support for modern OpenAPI features.

Dependencies

The generated code depends on:

dotnet add package Azure.Core
dotnet add package System.Text.Json

Basic Usage

using 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}");
        }
    }
}

Custom HTTP Client Configuration

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);

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:

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:

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:

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


Refitter

Refitter generates Refit interfaces from OpenAPI specifications, allowing you to use the declarative HTTP client library.

Dependencies

The generated code depends on:

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) // AutoRest
{
    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");
//     }
// }

// 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");
    });

General Best Practices

  1. Use Dependency Injection: Register clients with DI containers for better testability
  2. Handle Errors Gracefully: Always catch and handle API exceptions appropriately
  3. Use Cancellation Tokens: Support cancellation for long-running operations
  4. Configure Timeouts: Set appropriate timeouts to prevent hanging requests
  5. Implement Retry Logic: Use Polly or built-in retry mechanisms for resilience
  6. Secure API Keys: Store API keys and secrets securely, never in code
  7. Log API Calls: Implement logging for debugging and monitoring

Support

For issues or questions specific to the code generators:

For issues with this tool itself, please visit the REST API Client Code Generator Issues.