wasAsked.

How do you integrate external APIs into your application ?

Capgemini · Full Stack Developer · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

A reliable integration treats the external API as something that can be slow, fail, change or be abused. 1. Typed HTTP client through IHttpClientFactory builder.Services.AddHttpClient<PaymentGatewayClient>(client => { client.BaseAddress = new Uri(builder.Configuration["Payments:BaseUrl"]!); client.Timeout = Timeout.InfiniteTimeSpan; // timeouts handled by the resilience pipeline }) .AddStandardResilienceHandler(); // retries, timeouts, circuit breaker (Polly v8) - IHttpClientFactory manages handler lifetimes, avoiding socket exhaustion and stale DNS issues. - The typed client encapsulates URLs, serialization and error mapping: public sealed class PaymentGatewayClient(HttpClient http, ILogger<PaymentGatewayClient> log) { public async Task<PaymentResult> ChargeAsync(ChargeRequest req, CancellationToken ct) { using var msg = new HttpRequestMessage(HttpMethod.Post, "v1/charges") { Content = JsonContent.Create(req) }; msg.Headers.Add("Idempotency-Key", req.IdempotencyKey); using var res = await http.SendAsync(msg, ct); if (res.StatusCode == HttpStatusCode.UnprocessableEntity) return PaymentResult.Declined(await res.Content.ReadAsStringAsync(ct)); res.EnsureSuccessStatusCode(); return (await res.Content.ReadFromJsonAsync<PaymentResult>(ct))!; } } 2. Authentication and secrets - API keys, client secrets or certificates stored in Key Vault (never in code); OAuth client credentials tokens cached and refreshed in a DelegatingHandler. 3. Resilience - Timeouts on every call, retries with backoff and jitter for transient errors only (and only for idempotent operations or with idempotency keys), circuit breakers, and fallbacks (cached data or degraded features). - Respect the provider's rate limits (429 with Retry-After). 4. Data contracts - Separate DTOs for the external API, mapped to internal models (an anti-corruption layer) so provider changes do not ripple through the codebase. - Tolerant deserialization (ignore unknown fields), and validation of critical response data. 5. Asynchronous patterns where suitable - For slow or non-urgent operations, call the provider from a background worker via a queue; for providers that use webhooks, verify signatures and handle duplicate deliveries. 6. Observability - Log requests and responses at an appropriate level without sensitive data; dependency tracking in Application Insights or OpenTelemetry shows latency and failures per provider; alerts on error rates. 7. Testing - Unit tests with a mocked HttpMessageHandler, integration tests with WireMock.Net simulating timeouts and errors, and occasional tests against the provider's sandbox.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics