Skip to content

Use Cases for the ConnectSoft API Library Template

The ConnectSoft API Library Template is designed to streamline the development of service agent libraries in .NET Core. It simplifies API integrations by providing pre-configured components, robust patterns, and extensibility. This document explores practical use cases and real-world scenarios where the template adds significant value.

Core Use Cases

Third-Party API Integrations

Scenario

A company needs to interact with external APIs such as Google Analytics, Stripe, AWS, or payment gateways.

Solution

Use the API Library Template to create a service agent library that encapsulates API interaction logic.

Benefits

  • Abstracts complex API calls into reusable, strongly-typed methods
  • Provides built-in resiliency to handle API rate limits and failures
  • Ensures consistent error handling and logging across integrations

Implementation Example: Google Analytics API

dotnet new connectsoft-api-library \
  --name ConnectSoft.GoogleAnalytics \
  --api-service-name "GoogleAnalytics" \
  --api-service-description "Google Analytics Measurement Protocol API" \
  --authentication-type "ApiKey"

Configuration (appsettings.json):

{
  "GoogleAnalyticsService": {
    "BaseUrl": "https://www.google-analytics.com",
    "DefaultTimeout": "00:00:30",
    "ApiKeyAuthentication": {
      "ApiKey": "your-google-analytics-api-key",
      "HeaderName": "X-API-Key"
    },
    "EnableHttpStandardResilience": true,
    "HttpStandardResilience": {
      "Retry": {
        "MaxRetryAttempts": 3,
        "Delay": "00:00:02"
      }
    }
  }
}

Usage:

public class AnalyticsController : ControllerBase
{
    private readonly IGoogleAnalyticsService _analyticsService;

    public AnalyticsController(IGoogleAnalyticsService analyticsService)
    {
        _analyticsService = analyticsService;
    }

    [HttpPost("track")]
    public async Task<IActionResult> TrackEvent([FromBody] AnalyticsEvent evt)
    {
        var result = await _analyticsService.TrackEventAsync(evt);
        return Ok(result);
    }
}

Internal Microservice Communication

Scenario

A microservices-based system requires standardized communication between services.

Solution

Create libraries for internal APIs to ensure consistency and simplify service-to-service calls.

Benefits

  • Encourages code reuse and reduces duplication
  • Ensures robust communication through retries, circuit breakers, and rate limiting
  • Provides consistent error handling and logging

Implementation Example: Internal Billing API

dotnet new connectsoft-api-library \
  --name ConnectSoft.BillingAPI \
  --api-service-name "BillingService" \
  --api-service-description "Internal Billing Microservice API" \
  --authentication-type "OAuth"

Configuration:

{
  "BillingService": {
    "BaseUrl": "https://billing.internal.example.com",
    "OAuth2Authentication": {
      "OAuthHttpHandler": {
        "OAuth2Options": {
          "TokenEndpoint": "https://auth.internal.example.com/oauth2/token",
          "ClientId": "billing-client-id",
          "ClientSecret": "billing-client-secret",
          "GrantType": "ClientCredentials",
          "Scope": [ "billing.read", "billing.write" ]
        }
      }
    },
    "EnableHttpStandardResilience": true
  }
}

Multi-Tenant SaaS Applications

Scenario

A SaaS platform requires API interactions that vary per tenant.

Solution

Use the options pattern to configure tenant-specific settings for API calls.

Benefits

  • Simplifies configuration management for multi-tenant systems
  • Isolates tenant data securely
  • Supports tenant-specific authentication and endpoints

Implementation Example: Tenant-Aware Payment API

dotnet new connectsoft-api-library \
  --name ConnectSoft.PaymentGateway \
  --api-service-name "PaymentGateway" \
  --api-service-description "Payment Gateway API with tenant support" \
  --authentication-type "ApiKey"

Multi-Tenant Configuration:

// Register tenant-specific configurations
services.Configure<PaymentGatewayOptions>("Tenant1", options =>
{
    options.BaseUrl = "https://api.tenant1.paymentgateway.com";
    options.ApiKeyAuthentication.ApiKey = "tenant1-api-key";
});

services.Configure<PaymentGatewayOptions>("Tenant2", options =>
{
    options.BaseUrl = "https://api.tenant2.paymentgateway.com";
    options.ApiKeyAuthentication.ApiKey = "tenant2-api-key";
});

Authentication Type-Specific Use Cases

None Authentication

Use Case: Public Weather API

Scenario: Integrate with a public weather API that doesn't require authentication.

dotnet new connectsoft-api-library \
  --name ConnectSoft.WeatherAPI \
  --api-service-name "WeatherService" \
  --api-service-description "Public Weather API" \
  --authentication-type "None"

Configuration:

{
  "WeatherService": {
    "BaseUrl": "https://api.openweathermap.org",
    "DefaultTimeout": "00:00:30"
  }
}

Basic Authentication

Use Case: Legacy System Integration

Scenario: Integrate with a legacy system that uses HTTP Basic Authentication.

dotnet new connectsoft-api-library \
  --name ConnectSoft.LegacySystem \
  --api-service-name "LegacySystem" \
  --api-service-description "Legacy System API with Basic Auth" \
  --authentication-type "Basic"

Configuration:

{
  "LegacySystem": {
    "BaseUrl": "https://legacy.example.com",
    "BasicAuthentication": {
      "Username": "legacy-user",
      "Password": "legacy-password"
    }
  }
}

Security Note: Always use HTTPS with Basic Authentication.

API Key Authentication

Use Case: Stripe Payment Integration

Scenario: Integrate with Stripe for payment processing.

dotnet new connectsoft-api-library \
  --name ConnectSoft.Stripe \
  --api-service-name "StripeClient" \
  --api-service-description "Stripe Payment API" \
  --authentication-type "ApiKey"

Configuration:

{
  "StripeClient": {
    "BaseUrl": "https://api.stripe.com",
    "ApiKeyAuthentication": {
      "ApiKey": "sk_test_your_stripe_key",
      "HeaderName": "Authorization"
    },
    "EnableHttpStandardResilience": true
  }
}

Usage:

public class PaymentService
{
    private readonly IStripeClient _stripeClient;

    public PaymentService(IStripeClient stripeClient)
    {
        _stripeClient = stripeClient;
    }

    public async Task<PaymentResult> ProcessPaymentAsync(PaymentRequest request)
    {
        return await _stripeClient.CreateChargeAsync(request);
    }
}

OAuth2 Authentication

Use Case: Microsoft Graph API

Scenario: Integrate with Microsoft Graph API for Office 365 data.

dotnet new connectsoft-api-library \
  --name ConnectSoft.MicrosoftGraph \
  --api-service-name "MicrosoftGraphClient" \
  --api-service-description "Microsoft Graph API Client" \
  --authentication-type "OAuth"

Configuration:

{
  "MicrosoftGraphClient": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "OAuth2Authentication": {
      "OAuthHttpHandler": {
        "OAuth2Options": {
          "TokenEndpoint": "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token",
          "ClientId": "your-azure-ad-client-id",
          "ClientSecret": "your-azure-ad-client-secret",
          "GrantType": "ClientCredentials",
          "Scope": [ "https://graph.microsoft.com/.default" ]
        }
      }
    }
  }
}

OpenID Connect Authentication

Use Case: Enterprise Identity Provider Integration

Scenario: Integrate with an enterprise API that requires OpenID Connect token validation.

dotnet new connectsoft-api-library \
  --name ConnectSoft.EnterpriseAPI \
  --api-service-name "EnterpriseService" \
  --api-service-description "Enterprise API with OpenID Connect" \
  --authentication-type "OpenIDConnect"

Configuration:

{
  "EnterpriseService": {
    "BaseUrl": "https://api.enterprise.example.com",
    "OAuth2Authentication": {
      "OAuthHttpHandler": {
        "OAuth2Options": {
          "TokenEndpoint": "https://idp.enterprise.example.com/oauth2/token",
          "ClientId": "enterprise-client-id",
          "ClientSecret": "enterprise-client-secret",
          "GrantType": "ClientCredentials",
          "Scope": [ "api.read", "api.write" ]
        }
      },
      "OpenIdConnect": {
        "Authority": "https://idp.enterprise.example.com",
        "ValidIssuers": [
          "https://idp.enterprise.example.com"
        ],
        "ValidAudiences": [ "enterprise-client-id" ],
        "ValidateLifetime": true,
        "ValidateIssuerSigningKey": true
      }
    }
  }
}

Advanced Use Cases

Real-Time API Interactions

Scenario

An application needs to send and receive data in real-time, such as stock price updates or IoT telemetry.

Solution

Use the API Library Template to manage API calls with resiliency patterns for high-frequency requests.

Benefits

  • Handles transient failures with retries and circuit breakers
  • Ensures consistent performance under load
  • Rate limiting prevents API throttling

Implementation Example: IoT Telemetry API

dotnet new connectsoft-api-library \
  --name ConnectSoft.IoTTelemetry \
  --api-service-name "TelemetryService" \
  --api-service-description "IoT Telemetry API" \
  --authentication-type "ApiKey" \
  --use-metrics

Configuration with Rate Limiting:

{
  "TelemetryService": {
    "BaseUrl": "https://telemetry.example.com",
    "ApiKeyAuthentication": {
      "ApiKey": "iot-api-key",
      "HeaderName": "X-API-Key"
    },
    "EnableHttpStandardResilience": true,
    "HttpStandardResilience": {
      "RateLimiter": {
        "DefaultRateLimiterOptions": {
          "PermitLimit": 100,
          "QueueLimit": 50
        }
      },
      "Retry": {
        "MaxRetryAttempts": 2,
        "Delay": "00:00:01"
      }
    }
  }
}

Fault-Tolerant Systems

Scenario

Applications need to remain operational even when an external API experiences downtime.

Solution

Leverage chaos testing and resiliency features to validate fault tolerance.

Benefits

  • Ensures the system gracefully degrades or falls back during failures
  • Validates circuit breaker and retry mechanisms
  • Tests timeout handling under failure conditions

Implementation Example: Critical Service Integration

dotnet new connectsoft-api-library \
  --name ConnectSoft.CriticalService \
  --api-service-name "CriticalService" \
  --api-service-description "Critical External Service" \
  --authentication-type "OAuth" \
  --use-metrics

Configuration with Comprehensive Resiliency:

{
  "CriticalService": {
    "BaseUrl": "https://critical.example.com",
    "EnableHttpStandardResilience": true,
    "HttpStandardResilience": {
      "TotalRequestTimeout": { "Timeout": "00:00:30" },
      "Retry": {
        "MaxRetryAttempts": 5,
        "BackoffType": "Exponential",
        "UseJitter": true,
        "Delay": "00:00:01",
        "MaxDelay": "00:00:10"
      },
      "CircuitBreaker": {
        "FailureRatio": 0.1,
        "MinimumThroughput": 10,
        "SamplingDuration": "00:01:00",
        "BreakDuration": "00:00:30"
      },
      "AttemptTimeout": { "Timeout": "00:00:10" }
    },
    "EnableChaosInjection": false  // Enable for testing only
  }
}

Multi-Region Deployments

Scenario

A global application requires API interactions optimized for specific regions.

Solution

Use region-specific configurations for base URLs and headers.

Benefits

  • Reduces latency and improves user experience for global users
  • Supports region-specific authentication
  • Enables region-specific resiliency configurations

Implementation Example: Regional API Configuration

// Register region-specific configurations
services.Configure<MyServiceOptions>("EU", options =>
{
    options.BaseUrl = "https://eu.api.example.com";
    options.ApiKeyAuthentication.ApiKey = "eu-api-key";
    options.DefaultTimeout = TimeSpan.FromSeconds(30);
});

services.Configure<MyServiceOptions>("US", options =>
{
    options.BaseUrl = "https://us.api.example.com";
    options.ApiKeyAuthentication.ApiKey = "us-api-key";
    options.DefaultTimeout = TimeSpan.FromSeconds(30);
});

services.Configure<MyServiceOptions>("Asia", options =>
{
    options.BaseUrl = "https://asia.api.example.com";
    options.ApiKeyAuthentication.ApiKey = "asia-api-key";
    options.DefaultTimeout = TimeSpan.FromSeconds(30);
});

Real-World Examples

Payment Gateway Integration

Scenario

A retail company integrates Stripe for processing payments.

Solution

Create a library for handling payment requests and responses using the template.

Implementation:

dotnet new connectsoft-api-library \
  --name ConnectSoft.Stripe \
  --api-service-name "StripeClient" \
  --api-service-description "Stripe Payment API Client" \
  --authentication-type "ApiKey" \
  --use-metrics

Features Used:

  • API Key authentication
  • Standard resilience handler for retry and circuit breaker
  • Metrics for tracking payment processing
  • Mock server testing for payment scenarios

Analytics Integration

Scenario

A marketing platform integrates with Google Analytics for tracking events.

Solution

Use the template to encapsulate analytics event tracking logic.

Implementation:

dotnet new connectsoft-api-library \
  --name ConnectSoft.GoogleAnalytics \
  --api-service-name "GoogleAnalytics" \
  --api-service-description "Google Analytics Measurement Protocol" \
  --authentication-type "ApiKey"

Features Used:

  • API Key authentication
  • Resiliency patterns for reliable event tracking
  • Metrics for tracking API usage

IoT Platform API

Scenario

An IoT platform requires frequent data uploads from devices to a central API.

Solution

Build a library to manage telemetry uploads with rate limiting and retries.

Implementation:

dotnet new connectsoft-api-library \
  --name ConnectSoft.IoTPlatform \
  --api-service-name "IoTPlatformClient" \
  --api-service-description "IoT Platform Telemetry API" \
  --authentication-type "OAuth" \
  --use-metrics

Features Used:

  • OAuth2 authentication for secure device authentication
  • Rate limiting to prevent API throttling
  • Metrics for monitoring telemetry uploads
  • Resiliency for handling network issues

Authentication Type Selection Guidance

Decision Matrix

API Type Recommended Authentication Reason
Public API None No authentication required
Legacy System Basic Simple username/password
Modern REST API ApiKey Most common, simple to implement
Enterprise API OAuth Token-based, secure, standard
Identity Provider Integration OpenIDConnect Token validation, SSO support

Selection Criteria

  1. API Requirements: Check the API documentation for supported authentication methods
  2. Security Level: Consider the sensitivity of data and operations
  3. Token Management: OAuth/OpenIDConnect provide automatic token refresh
  4. Complexity: ApiKey is simplest, OpenIDConnect is most complex
  5. Integration: Consider existing identity infrastructure

Benefits of Using the Template

Standardization

  • Ensures all API libraries adhere to consistent patterns and practices
  • Reduces learning curve for new team members
  • Facilitates code reviews and maintenance

Resiliency

  • Protects against transient failures and external API downtime
  • Validates fault tolerance through chaos testing
  • Provides configurable retry, circuit breaker, and timeout strategies

Scalability

  • Supports high-throughput use cases with advanced configurations
  • Rate limiting prevents API throttling
  • Connection pooling optimizes resource usage

Developer Efficiency

  • Reduces setup time and allows teams to focus on business logic
  • Pre-configured testing infrastructure
  • Automated CI/CD pipelines

Best Practices by Use Case

Third-Party Integrations

  1. Use API Key Authentication: Most third-party APIs use API keys
  2. Enable Resiliency: External APIs are more likely to have transient failures
  3. Monitor Metrics: Track API usage and failures
  4. Mock Server Testing: Test without hitting real API limits

Internal Microservices

  1. Use OAuth2: Secure token-based authentication
  2. Configure Hedging: Multiple service instances benefit from hedging
  3. Lower Timeouts: Internal services should respond faster
  4. Comprehensive Testing: Test with real services in integration tests

Multi-Tenant SaaS

  1. Tenant-Specific Configuration: Use named options for tenant isolation
  2. Secure Storage: Store tenant credentials securely (Key Vault)
  3. Rate Limiting: Prevent one tenant from affecting others
  4. Monitoring: Track per-tenant API usage

Conclusion

The ConnectSoft API Library Template is a versatile tool that supports a wide range of use cases, from third-party SDK development to internal microservice communication. By abstracting API interactions and embedding best practices, the template empowers developers to build reliable, maintainable, and scalable libraries.

Each use case benefits from the template's built-in features:

  • Typed HTTP Clients: Type-safe API interactions
  • Resiliency Patterns: Fault tolerance and reliability
  • Authentication Support: Multiple authentication mechanisms
  • Testing Infrastructure: Mock server and unit testing
  • Observability: Metrics and logging

By choosing the appropriate authentication type and configuring resiliency patterns, you can build API client libraries that meet your specific requirements while following industry best practices.

For more information, see: