HTTP External API Integration
Files Referenced in this Document
- IMyPluginNameExternalApi.cs
- MyPluginNameProjectService.cs
- appsettings.json
- CMS.Plugin.MyPluginName.csproj
- MyEntityNameCreateDto.cs
Table of Contents
- Introduction
- Type-Safe HTTP API Definition
- Dependency Injection and HttpClientFactory Integration
- API Call Example
- Configuration Management
- Error Handling and Logging
- Resilience Patterns and Polly Integration Suggestions
- Secure Communication Configuration
- Compatibility with ABP Remote Service Calls
- Summary
Introduction
This document details the type-safe HTTP API integration scheme based on WebApiClientCore. This scheme implements type-safe external API calls by defining interface contracts, ensuring compile-time checks and consistent development experience. The system manages the API client lifecycle through the dependency injection container and integrates with HttpClientFactory to achieve efficient HTTP connection management.
Type-Safe HTTP API Definition
Based on the WebApiClientCore framework, RESTful API contracts are declared by defining interfaces to achieve type-safe HTTP calls. The IMyPluginNameExternalApi interface uses attributes to describe various aspects of HTTP requests.
The interface defines asynchronous method signatures, returning Task<T> types to support non-blocking calls. The request path is specified as /api/v1/myPluginName/myEntityName via the [HttpPost] attribute, complying with RESTful design specifications. JSON serialization is automatically handled by WebApiClientCore, and the request body is marked with the [JsonContent] attribute, ensuring the DTO object is correctly serialized into JSON format.
Section sources
Dependency Injection and HttpClientFactory Integration
WebApiClientCore integrates seamlessly with ASP.NET Core's dependency injection system and HttpClientFactory. Although specific registration code is not shown in the provided files, according to WebApiClientCore's standard practices, API interfaces need to be registered in the service container.
Usually, the services.AddHttpApi<IMyPluginNameExternalApi>() extension method is used in the module's ConfigureServices method to register the API interface. This registration mechanism automatically integrates the interface with HttpClientFactory, leveraging named HttpClient and typed HttpClient to achieve connection pooling, lifecycle management, and centralized configuration.
This integration method avoids common issues with manually managing HttpClient instances (such as Socket exhaustion) while maintaining a type-safe API call experience.
Section sources
API Call Example
In MyPluginNameProjectService, the IMyPluginNameExternalApi instance is resolved through the IServiceProvider obtained via dependency injection to call the external API. The ExecuteExternalApiAsync method demonstrates the actual call pattern.
This method obtains the API interface instance via the service provider, then calls the CreateAsync method passing a MyEntityNameCreateDto object. The call is asynchronous, complying with modern .NET application best practices. The DTO object contains necessary properties (such as Name and Code), which will be serialized into the JSON request body.
Diagram sources
Section sources
Configuration Management
External API configuration is managed through the appsettings.json file, following the best practice of separating configuration from code. Configuration items use the API interface name IMyPluginNameExternalApi as the configuration section, containing the HttpHost property to specify the base address of the external API.
This configuration method allows using different API endpoints in different environments (development, testing, production) without modifying code. Configuration can be overridden at runtime, for example via environment variables or database configuration, ensuring deployment flexibility.
It is suggested to store sensitive configuration (such as API keys) in safer locations (like environment variables or key management services) to avoid storing them in plaintext in configuration files.
Section sources
Error Handling and Logging
The system implements a robust error handling mechanism, using try-catch blocks in the ExecuteExternalApiAsync method to capture all exceptions. Upon capturing an exception, it logs exception information via the injected ILogger instance, ensuring issues are traceable and diagnosable.
Logging uses structured logs, including full stack traces of exceptions, facilitating troubleshooting. This pattern ensures that even if external API calls fail, it does not cause the main application to crash, while providing sufficient diagnostic information.
For specific HTTP error status codes (such as 400, 404, 500, etc.), WebApiClientCore throws corresponding exceptions, which can be handled more granularly in the catch block.
Section sources
Resilience Patterns and Polly Integration Suggestions
To improve system resilience and reliability, it is recommended to integrate the Polly library to implement resilience patterns such as retry and circuit breaker. For external API calls, network faults and transient errors are common issues, and Polly can effectively handle these scenarios.
Retry strategies based on HTTP status codes (such as exponential backoff retry for 5xx errors) can be configured, or circuit breaker patterns can be implemented to fail fast when services are continuously unavailable. These strategies can be combined with HttpClientFactory, implemented by adding DelegatingHandler or using advanced configuration of IHttpClientFactory.
Although current code does not implement Polly integration, it is a recommended enhancement direction, especially when facing unstable external dependencies in production environments.
Secure Communication Configuration
For production environments, it is recommended to use HTTPS/TLS encrypted communication to protect data security. This requires configuring HttpHost in appsettings.json as an HTTPS address (starting with https://).
In addition, appropriate certificate validation policies should be configured to ensure secure connections with external API servers. HttpClient's SSL options can be configured to handle custom certificates or specific TLS version requirements. For APIs requiring authentication, appropriate authentication headers (such as Bearer Token or API Key) should be included in requests.
Section sources
Compatibility with ABP Remote Service Calls
This integration scheme is compatible with the ABP framework's remote service call pattern. ABP provides its own remote service call mechanism, but WebApiClientCore can serve as a supplementary scheme for calling APIs of external systems (non-ABP systems).
Both modes can coexist: using ABP's proxy client to call other ABP module APIs, while using WebApiClientCore to call external third-party APIs. This hybrid mode provides maximum flexibility, allowing the system to interact with various internal and external services.
Summary
This document detailed the type-safe HTTP API integration scheme based on WebApiClientCore. By defining RESTful contracts via interfaces, compile-time safe API calls are achieved. The system integrates with dependency injection and HttpClientFactory, ensuring efficient resource management and configuration flexibility. The MyPluginNameProjectService example demonstrated the actual call pattern and provided guidance on error handling, logging, and secure communication. It is recommended to further integrate Polly to enhance system resilience, especially when facing unstable external dependencies.