Karsoe.ApiGenerator
1.0.2
dotnet tool install --global Karsoe.ApiGenerator --version 1.0.2
dotnet new tool-manifest
dotnet tool install --local Karsoe.ApiGenerator --version 1.0.2
#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.
π 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
As a Global Tool (Recommended)
# 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
Prepare your OpenAPI specification file (JSON or YAML)
Generate the API client:
karsoe-api-gen -i swagger.json -o ./Generated -n MyApp.ApiClient
- 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
- Configure in your DI container:
services.AddHttpClient<ApiClient>(client =>
{
client.BaseAddress = new Uri("https://api.example.com");
})
.AddPolicyHandler(GetRetryPolicy());
- 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:
- 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");
});
- Custom retry policy:
.AddTransientHttpErrorPolicy(policy =>
policy.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
- Authentication:
services.AddHttpClient<ApiClient>()
.AddHttpMessageHandler<AuthenticationHandler>();
π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments
- Built with Microsoft.OpenApi.Readers
- Code generation powered by Scriban
- Resilience patterns with Polly
β Troubleshooting
Tool Installation Issues
Problem: dotnet tool install fails with error
Solution:
Uninstall existing version first:
dotnet tool uninstall --global Karsoe.ApiGeneratorClean and rebuild:
dotnet clean dotnet pack --configuration ReleaseInstall from Release folder:
dotnet tool install --global --add-source ./bin/Release Karsoe.ApiGenerator
Problem: Tool command not found after installation
Solution:
Verify installation:
dotnet tool list --globalEnsure .NET tools path is in your PATH environment variable:
- Windows:
%USERPROFILE%\.dotnet\tools - macOS/Linux:
$HOME/.dotnet/tools
- Windows:
Problem: Pack fails with errors
Solution:
Check .NET SDK version (requires .NET 10.0+):
dotnet --versionRestore packages:
dotnet restore
π Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
οΏ½ Publishing to NuGet
This project includes automated GitHub Actions workflows for publishing to NuGet.
Setup
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.*
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
Update the version in karsoe-api-generator.csproj:
<Version>1.0.1</Version>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 --tagsThe 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 | Versions 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. |
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.