API Library Template¶
The ConnectSoft API Library Template is a comprehensive framework for creating robust, reusable, and scalable service agent libraries in .NET Core. Designed for modern cloud-native and enterprise architectures, this template provides developers with all the tools needed to streamline the development of API integrations, ensure code quality, and adhere to industry best practices.
Introduction¶
Purpose¶
The API Library Template is a pre-configured solution that simplifies the process of building libraries for interacting with external APIs. Whether integrating with third-party platforms, creating SDKs for internal microservices, or developing reusable components for multi-tenant SaaS systems, this template ensures consistency, reliability, and scalability.
The template provides a production-ready foundation for building API service agent libraries that can be shared across projects, published as NuGet packages, and integrated into larger solutions. It follows Microsoft's .NET library design guidelines and incorporates best practices for HTTP client management, resiliency, authentication, and observability.
When to Use This Template¶
- Creating service agent libraries for external API integrations
- Building SDKs for third-party services (e.g., Google Analytics, Stripe, AWS)
- Developing libraries for internal microservice communication
- Creating tenant-aware libraries for SaaS platforms
- Building libraries that require multiple authentication mechanisms
- Developing libraries that need advanced resiliency patterns
- Publishing API client libraries as NuGet packages with CI/CD automation
When to Use Library Template Instead¶
Use the Library Template when: - Building general-purpose utility libraries without HTTP client needs - Creating domain model or business logic libraries - Developing libraries that don't interact with external APIs - Building simple libraries without authentication or resiliency requirements
Prerequisites¶
- .NET SDK 8.0 or later (required)
- .NET SDK 9.0 (recommended for multi-targeting support)
- Visual Studio 2022 (v17.14+ for .slnx support) or JetBrains Rider
- Azure DevOps account (for CI/CD pipeline integration, optional)
- Python 3.x with pip (for MkDocs documentation, optional)
Template Scope¶
Generated Solution Structure¶
The template generates a complete solution with the following structure:
YourApiLibraryName/
├── src/
│ └── YourApiLibraryName/
│ ├── YourApiLibraryName.csproj
│ ├── I{ServiceName}Service.cs # Service interface
│ ├── {ServiceName}Service.cs # Service implementation
│ ├── {ServiceName}ServiceException.cs # Custom exceptions
│ ├── {ServiceName}Response.cs # Response models
│ ├── {ServiceName}Result.cs # Result models
│ ├── {ServiceName}Error.cs # Error models
│ ├── {ServiceName}ServiceExtensions.cs # DI extensions
│ ├── Options/ # Configuration options
│ │ ├── {ServiceName}ServiceOptions.cs
│ │ ├── Validate{ServiceName}ServiceOptions.cs
│ │ ├── ApiKeyAuthenticationOptions.cs (if ApiKey)
│ │ ├── BasicAuthenticationOptions.cs (if Basic)
│ │ ├── ChaosInjectionOptions.cs
│ │ └── WebProxyOptions.cs
│ ├── Metrics/ # (if UseMetrics=true)
│ │ └── {ServiceName}ServiceMetrics.cs
│ ├── Handlers/ # (empty, for custom handlers)
│ └── Resilience/ # (empty, for custom policies)
├── tests/
│ └── YourApiLibraryName.UnitTests/
│ ├── YourApiLibraryName.UnitTests.csproj
│ ├── {ServiceName}ServiceUnitTests.cs
│ ├── {ServiceName}ServiceWithMockedServerUnitTests.cs
│ ├── Metrics/ # (if UseMetrics=true)
│ │ └── {ServiceName}ServiceMetricsUnitTests.cs
│ ├── appsettings.UnitTests.json
│ └── appsettings.MockedServerUnitTests.json
├── docs/ # MkDocs documentation structure
├── YourApiLibraryName.slnx # Modern solution format
├── YourApiLibraryName.sln # Legacy solution format
├── Directory.Build.props # Shared build properties
├── Directory.Packages.props # Central Package Management
├── azure-pipelines.yml # CI/CD pipeline
├── README.md # Templated documentation
├── .gitignore # Git ignore rules
└── nuget.config # NuGet feed configuration
Generated Projects¶
-
API Library Project: Main project containing your API client code
- Multi-targeting:
net8.0andnet9.0 - XML documentation generation enabled
- Static code analyzers configured
- Conditional feature folders based on template parameters
- Multi-targeting:
-
Unit Test Project: MSTest-based test project
- Code coverage collection configured
- WireMock.Net integration for mock server testing
- Conditional test projects for optional features
- Project reference to library project
Key Features¶
Typed HTTP Client¶
- HttpClientFactory Integration: Optimized connection pooling, DNS updates, and lifecycle management
- Strongly-Typed Interfaces: Predictable API interactions with type safety
- Connection Pooling: Efficient resource management and reuse
- Proxy Support: Configurable web proxy for HTTP requests
Authentication Mechanisms¶
- None: Public APIs without authentication
- Basic Authentication: Username/password with Base64 encoding
- API Key: Header-based API key authentication
- OAuth2: Token-based authentication with client credentials flow
- OpenID Connect: Identity provider integration with token validation
Resiliency Patterns¶
- Standard Resilience Handler: Retry, circuit breaker, timeout, bulkhead, rate limiter
- Standard Hedging Handler: Parallel request execution for slow dependencies
- Polly Integration: Advanced resilience patterns via Polly.Core
- Chaos Injection: Fault and latency injection for testing resiliency
Metrics and Observability¶
- OpenTelemetry Metrics: Custom metrics implementation
- Request Tracking: Counters and histograms for API calls
- Failure Monitoring: Error tracking by status code
- Performance Metrics: Request duration and throughput
Testing Support¶
- Mock Server: WireMock.Net integration for API simulation
- Unit Tests: MSTest-based unit testing
- Integration Tests: End-to-end testing capabilities
- Chaos Testing: Resiliency validation under failure conditions
Configuration and Options¶
- Options Pattern: Strongly-typed configuration with validation
- Nested Options: Complex configuration structures
- Environment Variables: Externalized configuration support
- Validation: DataAnnotations and source-generated validators
Complete Parameter Reference¶
| Parameter | Type | Required | Default | CLI Flag | Description |
|---|---|---|---|---|---|
ApiServiceName |
string | Yes | ExchangeRate |
--api-service-name |
Service name used in code (e.g., ExchangeRate, GoogleAnalytics) |
ApiServiceDescription |
string | Yes | Exchange rate |
--api-service-description |
Human-readable API description |
AuthenticationType |
choice | No | None |
--authentication-type |
Authentication mechanism: None, Basic, OAuth, OpenIDConnect, ApiKey |
buildDefinitionNumber |
string | No | "" |
-b, --build-definition-number |
Azure DevOps build definition number |
UseMetrics |
bool | No | true |
--use-metrics |
Enable built-in metrics support |
Framework |
choice | No | net8.0 |
-f, --framework |
Target framework: net8.0 or net9.0 |
For detailed parameter documentation, see the Parameters Guide.
Quick Start¶
Step 1: Install the Template¶
The template is available from Azure DevOps Artifacts. Ensure your NuGet feed is configured in nuget.config.
Step 2: Create a New API Library¶
dotnet new connectsoft-api-library \
--name ConnectSoft.GoogleAnalytics \
--api-service-name "GoogleAnalytics" \
--api-service-description "Google Analytics Measurement Protocol API" \
--authentication-type "ApiKey"
Step 3: Configure the Library¶
Update appsettings.json with your API configuration:
{
"GoogleAnalyticsService": {
"BaseUrl": "https://www.google-analytics.com",
"DefaultTimeout": "00:00:30",
"ApiKeyAuthentication": {
"ApiKey": "your-api-key",
"HeaderName": "X-API-Key"
}
}
}
Step 4: Register Services¶
services.AddGoogleAnalyticsOptions(configuration);
services.AddGoogleAnalyticsMetrics(); // if UseMetrics=true
services.AddGoogleAnalyticsService();
Step 5: Use the Service¶
public class MyController : ControllerBase
{
private readonly IGoogleAnalyticsService _service;
public MyController(IGoogleAnalyticsService service)
{
_service = service;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var result = await _service.GetDataAsync();
return Ok(result);
}
}
Architecture Overview¶
Design Principles¶
- Service Agent Pattern: Encapsulates API interaction logic
- HttpClientFactory Pattern: Proper HTTP client lifecycle management
- Options Pattern: Strongly-typed, validated configuration
- Resilience First: Built-in fault tolerance mechanisms
- Observability: Comprehensive logging, metrics, and tracing support
HTTP Client Architecture¶
- Typed Clients: Interface-based service definitions
- Connection Pooling: Efficient resource management
- Resilience Handlers: Standard and hedging patterns
- Authentication Handlers: Per-request authentication
- Proxy Support: Configurable web proxy
Project Organization¶
- Source Code: Organized in
src/folder with service-based structure - Tests: Separate test project in
tests/folder - Documentation: MkDocs-based documentation in
docs/folder - CI/CD: Azure Pipelines YAML in root directory
For detailed architecture information, see the Architecture Guide.
Key Differences from Library Template¶
| Feature | API Library Template | Library Template |
|---|---|---|
| Primary Purpose | HTTP API client libraries | General-purpose libraries |
| HTTP Client | Full HttpClientFactory integration | Not included |
| Authentication | Multiple auth types (None, Basic, ApiKey, OAuth, OpenIDConnect) | Not included |
| Resiliency | Standard resilience and hedging handlers | Not included |
| Chaos Testing | Built-in chaos injection | Not included |
| Mock Server | WireMock.Net integration | Not included |
| Proxy Support | Web proxy configuration | Not included |
| Service Pattern | Service agent pattern | General service pattern |
| Request/Response Models | Generated request/response structures | Not included |
| Exception Handling | API-specific exception classes | General exception handling |
Integration with ConnectSoft Framework¶
The API Library Template seamlessly integrates into the ConnectSoft Framework, allowing developers to:
- Reuse API client libraries across multiple projects
- Leverage pre-configured pipelines for consistent build, test, and publish processes
- Follow consistent patterns for API integration across the organization
- Share authentication and resiliency configurations
Next Steps¶
- Parameters Guide - Complete parameter reference and usage
- Generated Structure - Understanding what gets generated
- Features - Detailed feature documentation
- Architecture - Design principles and patterns
- Authentication - Authentication mechanisms
- Resiliency & Chaos - Resiliency patterns and chaos engineering
- Configuration - Options pattern and configuration
- Testing - Testing strategies and mock server
- Use Cases - Real-world examples and scenarios
- Development Guide - Local development workflow
- Runbook - CI/CD operations and troubleshooting
References¶
- Best Practices:
- Authentication:
- Resiliency: