Karsoe.ApiGenerator 1.0.2

dotnet tool install --global Karsoe.ApiGenerator --version 1.0.2
                    
This package contains a .NET tool you can call from the shell/command line.
dotnet new tool-manifest
                    
if you are setting up this repo
dotnet tool install --local Karsoe.ApiGenerator --version 1.0.2
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=Karsoe.ApiGenerator&version=1.0.2
                    
nuke :add-package Karsoe.ApiGenerator --version 1.0.2
                    

Karsoe API Generator

A powerful .NET command-line tool that generates strongly-typed C# API clients from OpenAPI/Swagger specifications. Built with modern .NET practices and comprehensive testing.

Coverage Tests .NET License

πŸš€ Features

  • Strongly-Typed API Clients - Generate type-safe C# clients from OpenAPI 3.0+ specifications
  • DTO Model Generation - Automatic creation of data transfer objects with validation attributes
  • Polly Integration - Built-in retry policies and resilience patterns
  • Logging Support - Integrated logging infrastructure with Microsoft.Extensions.Logging
  • Authentication Ready - Optional authentication handler generation
  • Comprehensive Documentation - Automatic README generation with usage examples
  • Validation Attributes - DataAnnotations for required fields, ranges, and patterns
  • XML Documentation - Full IntelliSense support with generated comments
  • Easy Installation - Available as a .NET global tool

πŸ“¦ Installation

# Install from NuGet (after publishing)
dotnet tool install --global Karsoe.ApiGenerator

# Or install from local build
dotnet pack --configuration Release
dotnet tool install --global --add-source ./bin/Release Karsoe.ApiGenerator

# If updating an existing installation:
dotnet tool update --global Karsoe.ApiGenerator

# Or manually uninstall and reinstall:
dotnet tool uninstall --global Karsoe.ApiGenerator
dotnet tool install --global --add-source ./bin/Release Karsoe.ApiGenerator

From Source

git clone https://github.com/jennermand/karsoe-api-generator.git
cd karsoe-api-generator
dotnet build
dotnet run -- --help

🎯 Quick Start

  1. Prepare your OpenAPI specification file (JSON or YAML)

  2. Generate the API client:

karsoe-api-gen -i swagger.json -o ./Generated -n MyApp.ApiClient
  1. Copy generated files to your project and install dependencies:
dotnet add package Microsoft.Extensions.Http
dotnet add package Microsoft.Extensions.Http.Polly
dotnet add package Polly
dotnet add package System.ComponentModel.Annotations
  1. Configure in your DI container:
services.AddHttpClient<ApiClient>(client =>
{
    client.BaseAddress = new Uri("https://api.example.com");
})
.AddPolicyHandler(GetRetryPolicy());
  1. Use the generated client:
var client = serviceProvider.GetRequiredService<ApiClient>();
var products = await client.GetProductsAsync();

πŸ“– Usage

Basic Usage

karsoe-api-gen -i <input-file> -o <output-directory> -n <namespace>

Command-Line Options

Option Alias Description Default
--input -i Path to OpenAPI specification file (JSON/YAML) swagger.json
--output -o Output directory for generated files ./Generated
--namespace -n Namespace for generated code GeneratedApi
--no-auth - Skip authentication handler generation (enabled)
--no-retry - Skip Polly retry policy generation (enabled)
--no-logging - Skip logging infrastructure (enabled)
--no-readme - Skip README.md generation (enabled)
--no-validation - Skip validation attributes on models (enabled)
--help -h Show help message -

Examples

Generate with all defaults
karsoe-api-gen -i api-spec.json

Output: ./Generated/ with namespace GeneratedApi

Custom namespace and output
karsoe-api-gen -i swagger.json -o ./src/ApiClient -n MyCompany.ApiClient
Minimal generation (no auth, retry, or logging)
karsoe-api-gen -i api.json -o ./client -n Api --no-auth --no-retry --no-logging
Generate without validation attributes
karsoe-api-gen -i swagger.json --no-validation

πŸ“‚ Generated Output

The tool generates the following structure:

Generated/
β”œβ”€β”€ ApiClient.cs           # Main API client with all endpoints
β”œβ”€β”€ README.md              # Usage documentation
└── Models/                # DTO models folder
    β”œβ”€β”€ ProductDTO.cs
    β”œβ”€β”€ OrderDTO.cs
    └── ...

Generated API Client Features

  • Type-safe methods for all API endpoints
  • Async/await support with proper cancellation
  • HttpClient best practices
  • Exception handling with meaningful error messages
  • Query string and route parameter handling
  • Request/response serialization with System.Text.Json
  • Optional retry policies with Polly
  • Logging support for debugging and monitoring

Generated Model Features

  • Nullable reference types support
  • Data validation attributes (Required, Range, StringLength, etc.)
  • JSON property names with proper casing
  • XML documentation from OpenAPI descriptions
  • Nested object support
  • Collection types (List, Array, Dictionary)

πŸ› οΈ Development

Prerequisites

  • .NET 10.0 SDK or later
  • Visual Studio 2022, VS Code, or Rider

Building

dotnet restore
dotnet build

Running

dotnet run -- -i swagger.json -o ./Generated -n TestApi

Testing

The project includes comprehensive unit tests with 92.39% code coverage.

# Run all tests
dotnet test

# Run tests with coverage
cd Tests
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

# Generate HTML coverage report
reportgenerator -reports:TestResults/coverage.cobertura.xml -targetdir:TestResults/CoverageReport -reporttypes:Html

Test Coverage

  • 123 unit tests across all components
  • 92.39% line coverage on core functionality
  • 98.73% method coverage

Coverage breakdown by component:

  • TypeMapper: 97.05%
  • ModelGenerator: 98.50%
  • ReadmeGenerator: 98.76%
  • ApiClientGenerator: 87.69%
  • OpenApiParser: 80.00%
  • GeneratorOptions: 65.07%

Project Structure

karsoe-api-generator/
β”œβ”€β”€ ApiClientGenerator.cs     # API client code generation
β”œβ”€β”€ ModelGenerator.cs          # DTO model generation
β”œβ”€β”€ OpenApiParser.cs           # OpenAPI spec parsing
β”œβ”€β”€ ReadmeGenerator.cs         # Documentation generation
β”œβ”€β”€ TypeMapper.cs              # OpenAPI to C# type mapping
β”œβ”€β”€ GeneratorOptions.cs        # Command-line options
β”œβ”€β”€ Program.cs                 # Entry point
β”œβ”€β”€ Tests/                     # Unit tests
β”‚   β”œβ”€β”€ ApiClientGeneratorTests.cs
β”‚   β”œβ”€β”€ ModelGeneratorTests.cs
β”‚   β”œβ”€β”€ OpenApiParserTests.cs
β”‚   β”œβ”€β”€ ReadmeGeneratorTests.cs
β”‚   β”œβ”€β”€ TypeMapperTests.cs
β”‚   └── GeneratorOptionsTests.cs
└── Generated/                 # Sample generated output

πŸ”§ Advanced Usage

Integration with CI/CD

# GitHub Actions example
- name: Generate API Client
  run: |
    dotnet tool install --global Karsoe.ApiGenerator
    karsoe-api-gen -i api/swagger.json -o src/ApiClient -n MyApp.Client
    
- name: Commit generated code
  run: |
    git add src/ApiClient
    git commit -m "Update API client"

Custom Configuration

For advanced scenarios, you can modify the generated code:

  1. Custom HttpClient configuration:
services.AddHttpClient<ApiClient>(client =>
{
    client.BaseAddress = new Uri("https://api.example.com");
    client.Timeout = TimeSpan.FromSeconds(30);
    client.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");
});
  1. Custom retry policy:
.AddTransientHttpErrorPolicy(policy => 
    policy.WaitAndRetryAsync(3, retryAttempt => 
        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
  1. Authentication:
services.AddHttpClient<ApiClient>()
    .AddHttpMessageHandler<AuthenticationHandler>();

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

❓ Troubleshooting

Tool Installation Issues

Problem: dotnet tool install fails with error

Solution:

  1. Uninstall existing version first:

    dotnet tool uninstall --global Karsoe.ApiGenerator
    
  2. Clean and rebuild:

    dotnet clean
    dotnet pack --configuration Release
    
  3. Install from Release folder:

    dotnet tool install --global --add-source ./bin/Release Karsoe.ApiGenerator
    

Problem: Tool command not found after installation

Solution:

  1. Verify installation:

    dotnet tool list --global
    
  2. Ensure .NET tools path is in your PATH environment variable:

    • Windows: %USERPROFILE%\.dotnet\tools
    • macOS/Linux: $HOME/.dotnet/tools

Problem: Pack fails with errors

Solution:

  1. Check .NET SDK version (requires .NET 10.0+):

    dotnet --version
    
  2. Restore packages:

    dotnet restore
    

πŸ“ž Support

οΏ½ Publishing to NuGet

This project includes automated GitHub Actions workflows for publishing to NuGet.

Setup

  1. Get a NuGet API Key:

    • Go to https://www.nuget.org/
    • Sign in or create an account
    • Go to API Keys β†’ Create
    • Name: GitHub Actions - Karsoe.ApiGenerator
    • Select scopes: Push new packages and package versions
    • Glob pattern: Karsoe.*
  2. Add the API Key to GitHub Secrets:

    • Go to your GitHub repository β†’ Settings β†’ Secrets and variables β†’ Actions
    • Click "New repository secret"
    • Name: NUGET_API_KEY
    • Value: Paste your NuGet API key
    • Click "Add secret"

Publishing a New Version

  1. Update the version in karsoe-api-generator.csproj:

    <Version>1.0.1</Version>
    
  2. Commit and tag the release:

    git add karsoe-api-generator.csproj
    git commit -m "Bump version to 1.0.1"
    git tag v1.0.1
    git push origin main --tags
    
  3. The workflow will automatically:

    • βœ… Run all tests (must pass 85% coverage threshold)
    • βœ… Build the project in Release mode
    • βœ… Pack the .NET tool
    • βœ… Publish to NuGet.org
    • βœ… Create a GitHub Release with the package

Workflows

  • CI Build (.github/workflows/ci.yml): Runs on every push/PR to main

    • Tests on Ubuntu, Windows, and macOS
    • Validates 85% code coverage threshold
    • Generates coverage reports
  • Publish to NuGet (.github/workflows/publish-nuget.yml): Runs on version tags

    • Runs full test suite
    • Publishes to NuGet.org
    • Creates GitHub Release

πŸ—ΊοΈ Roadmap

  • Support for OpenAPI 2.0 (Swagger)
  • Custom template support
  • Multiple language support (TypeScript, Python, etc.)
  • GraphQL support
  • Watch mode for auto-regeneration
  • NuGet package publication
  • Automated CI/CD with GitHub Actions

Made with ❀️ by Karsoe

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

Version Downloads Last Updated
1.0.2 89 2/15/2026
1.0.1 86 2/15/2026
1.0.0-preview.1 46 2/14/2026

Initial release with support for OpenAPI 3.0+, strongly-typed clients, DTO
     generation, Polly integration, and comprehensive validation.