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
- Conclusion
Introduction
This document details the type-safe HTTP API integration scheme based on WebApiClientCore. This scheme achieves type-safe external API calls by defining interface contracts, ensuring consistency in compile-time checks and development experience. The system manages API client lifecycles through dependency injection containers 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 implement 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, conforming to RESTful design specifications. JSON serialization is automatically handled by WebApiClientCore, and the request body is marked with the [JsonContent] attribute, ensuring DTO objects are 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 standard practices, API interfaces need to be registered in the service container.
Typically, 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 HttpClients and typed HttpClients to achieve connection pooling, lifecycle management, and centralized configuration.
This integration avoids common issues associated 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 via the IServiceProvider obtained through dependency injection to call the external API. The ExecuteExternalApiAsync method demonstrates the actual call pattern.
This method retrieves the API interface instance via the service provider, then calls the CreateAsync method passing a MyEntityNameCreateDto object. The call is asynchronous, conforming to modern .NET application best practices. The DTO object contains necessary properties (like Name and Code), which will be serialized into a JSON request body.
Diagram sources
Section sources
Configuration Management
External API configuration is managed via the appsettings.json file, following best practices for separation of configuration and 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, test, production) without modifying code. Configuration can be overridden at runtime, for example via environment variables or database configuration, ensuring deployment flexibility.
It is recommended to store sensitive configuration (like API keys) in more secure 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, capturing all exceptions using try-catch blocks in the ExecuteExternalApiAsync method. Upon capturing an exception, error information is logged via the injected ILogger instance, ensuring issues are traceable and diagnosable.
Logging uses structured logs containing 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 (like 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 failures and transient errors are common issues, which Polly can handle effectively.
Retry policies based on HTTP status codes (e.g., 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 policies can be used in conjunction with HttpClientFactory by adding DelegatingHandlers or using advanced configuration of IHttpClientFactory.
Although the current code does not implement Polly integration, this 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 to an HTTPS address (starting with https://).
Additionally, 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 (like 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).
The two modes can coexist: using ABP's proxy client to call APIs of other ABP modules, 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.
Conclusion
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 suggested to further integrate Polly to enhance system resilience, especially when facing unstable external dependencies.