Tuesday, November 4, 2025

thumbnail

Integrating External APIs in Full Stack .NET Applications

 ๐ŸŒ Integrating External APIs in Full Stack .NET Applications — Complete Guide (2025)

๐Ÿงฉ 1. What Does “Integrating External APIs” Mean?


When building full-stack applications (frontend + backend + database), your app often needs to consume data or services from external sources, such as:


Payment gateways (Stripe, PayPal)


Mapping APIs (Google Maps)


Weather or stock data APIs


Authentication services (OAuth, Microsoft Identity)


AI services (OpenAI, Azure Cognitive Services)


Integration means your .NET backend acts as a bridge — it makes HTTP requests to those external APIs, processes their responses, and delivers the results to your frontend (Angular, React, or Blazor).


๐Ÿงฑ 2. Full-Stack Architecture Overview


Typical full-stack .NET setup:


[Frontend: React / Angular / Blazor]

          │

          ▼

[Backend: ASP.NET Core Web API]

          │

          ▼

[External APIs: e.g., OpenAI, Stripe, Weather API]

          │

          ▼

[Database: SQL Server / Cosmos DB]



The frontend sends a request to your ASP.NET Core API.


The backend calls the external API securely.


The response is processed, possibly stored, and returned to the frontend.


⚙️ 3. Backend Implementation (ASP.NET Core)

Step 1️⃣ – Create an API Project

dotnet new webapi -n ExternalApiDemo

cd ExternalApiDemo


Step 2️⃣ – Use HttpClient to Call the External API


Example: Integrate with a weather API


Services/WeatherService.cs


using System.Net.Http;

using System.Net.Http.Json;

using System.Threading.Tasks;


public class WeatherService

{

    private readonly HttpClient _httpClient;

    private readonly IConfiguration _config;


    public WeatherService(HttpClient httpClient, IConfiguration config)

    {

        _httpClient = httpClient;

        _config = config;

    }


    public async Task<object?> GetWeatherAsync(string city)

    {

        string apiKey = _config["WeatherApi:Key"];

        string baseUrl = _config["WeatherApi:BaseUrl"];


        var response = await _httpClient.GetFromJsonAsync<object>(

            $"{baseUrl}?q={city}&appid={apiKey}");


        return response;

    }

}


Step 3️⃣ – Register the Service in Program.cs

builder.Services.AddHttpClient<WeatherService>();


Step 4️⃣ – Create a Controller to Expose the Data


Controllers/WeatherController.cs


[ApiController]

[Route("api/[controller]")]

public class WeatherController : ControllerBase

{

    private readonly WeatherService _weatherService;


    public WeatherController(WeatherService weatherService)

    {

        _weatherService = weatherService;

    }


    [HttpGet("{city}")]

    public async Task<IActionResult> GetWeather(string city)

    {

        var data = await _weatherService.GetWeatherAsync(city);

        return Ok(data);

    }

}


๐Ÿ’ฌ 4. Frontend Integration (Angular/React/Blazor)

Example: Angular


weather.service.ts


getWeather(city: string): Observable<any> {

  return this.http.get(`/api/weather/${city}`);

}



This makes a call to your .NET backend, which then fetches data from the external API.


๐Ÿ” 5. Secure Your API Integration

✅ Best Practices


Never expose API keys in frontend code.


Store them in appsettings.json or better, in Azure Key Vault or User Secrets.


Use Dependency Injection for HttpClient


Avoid creating new HttpClient() directly — use IHttpClientFactory for performance and reliability.


Add Retry & Timeout Policies


Use Polly library for resilient API calls:


builder.Services.AddHttpClient<WeatherService>()

    .AddTransientHttpErrorPolicy(p => p.RetryAsync(3))

    .AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));



Validate and Sanitize Responses


Don’t trust external data — validate structure and sanitize before storing or returning.


Use HTTPS Everywhere


Ensure all external and internal communications are over secure channels.


๐Ÿงฐ 6. Handling Common Scenarios

Scenario Recommended Approach

Rate limiting / throttling Use caching or schedule background jobs

Slow API responses Use async/await, caching, or circuit breakers

Authentication required (OAuth, Bearer Tokens) Use HttpClient.DefaultRequestHeaders.Authorization

Multiple external APIs Create separate typed HttpClients for each

๐Ÿง  7. Example with an Authenticated API


Example: Calling OpenAI API with Bearer Token


public class OpenAIService

{

    private readonly HttpClient _client;

    private readonly IConfiguration _config;


    public OpenAIService(HttpClient client, IConfiguration config)

    {

        _client = client;

        _config = config;

        _client.DefaultRequestHeaders.Authorization = 

            new AuthenticationHeaderValue("Bearer", _config["OpenAI:ApiKey"]);

    }


    public async Task<string> GetResponseAsync(string prompt)

    {

        var content = new StringContent(

            JsonSerializer.Serialize(new { model = "gpt-4o-mini", prompt }),

            Encoding.UTF8, "application/json");


        var response = await _client.PostAsync("https://api.openai.com/v1/completions", content);

        response.EnsureSuccessStatusCode();


        return await response.Content.ReadAsStringAsync();

    }

}


๐Ÿ“Š 8. Logging and Monitoring


Use Serilog or Application Insights to track API performance, response times, and failures.


Log every external request and response (but avoid sensitive info).


๐Ÿชœ 9. Testing External API Integrations


Unit tests: Mock the HttpClient using Moq or WireMock.Net


Integration tests: Use the real API in a test environment with test keys


Postman: Verify endpoints manually before front-end integration


⚡ 10. Deployment Considerations (Azure)


When deploying to Azure:


Use Azure App Configuration or Key Vault for storing API keys.


Set environment variables for secrets.


Scale using Azure App Service with built-in monitoring.


✅ Summary

Layer Role Example

Frontend Calls your API Angular / React component

Backend (ASP.NET Core) Calls external APIs securely HttpClient, Polly, DI

External API Provides external data or service Weather API, OpenAI

Security Protects keys and responses Azure Key Vault, HTTPS

Testing/Logging Ensures reliability Serilog, Moq, App Insights

Learn Dot Net Course in Hyderabad

Read More

Visit Our Quality Thought Institute in Hyderabad

Get Directions 



Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive