Consume External APIs in ASP.NET Core: Complete Beginner Guide
Modern applications rarely operate in isolation. Most web applications communicate with external services to retrieve data, process payments, send notifications, authenticate users, access cloud resources, or integrate with third-party platforms.
ASP.NET Core provides powerful tools for consuming external APIs, making it easy to send HTTP requests, process JSON responses, handle authentication, and build reliable integrations.
In this tutorial, you'll learn how to consume external APIs in ASP.NET Core using HttpClient, HttpClientFactory, and modern development practices.
- What Are External APIs?
- Understanding HTTP Requests
- Using HttpClient
- HttpClientFactory
- Reading JSON Responses
- Authentication Headers
- Handling Errors
- Dependency Injection
- Best Practices
- Common Mistakes
What Are External APIs?
An API (Application Programming Interface) allows different applications to communicate with each other.
External APIs are services provided by third parties that expose data or functionality through HTTP endpoints.
Common examples include:
- Weather APIs
- Payment gateways
- Social media APIs
- Maps and location services
- Email providers
- Cloud storage services
How API Requests Work
Most external APIs use HTTP requests and JSON responses.
| Method | Purpose |
|---|---|
| GET | Retrieve data |
| POST | Create data |
| PUT | Update data |
| DELETE | Remove data |
Using HttpClient
HttpClient is the primary class used to send HTTP requests in .NET.
using System.Net.Http;
HttpClient client = new HttpClient();
It supports GET, POST, PUT, DELETE, and other HTTP operations.
Making a GET Request
The following example retrieves data from an external API.
var response = await client.GetAsync(
"https://api.example.com/products");
response.EnsureSuccessStatusCode();
string json =
await response.Content.ReadAsStringAsync();
EnsureSuccessStatusCode throws an exception when the request fails.
Creating a Model
Create a class that matches the JSON response.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
Deserialize JSON Data
Use System.Text.Json to convert JSON into C# objects.
using System.Text.Json;
var products =
JsonSerializer.Deserialize
<List<Product>>(json);
Using HttpClientFactory
Microsoft recommends HttpClientFactory for managing HttpClient instances.
builder.Services.AddHttpClient();
This helps prevent socket exhaustion and improves performance.
Inject IHttpClientFactory
public class ProductService
{
private readonly
IHttpClientFactory _factory;
public ProductService(
IHttpClientFactory factory)
{
_factory = factory;
}
}
Create a Client Instance
var client =
_factory.CreateClient();
Sending POST Requests
APIs often require sending data.
var product = new Product
{
Name = "Keyboard",
Price = 49.99M
};
var response =
await client.PostAsJsonAsync(
"https://api.example.com/products",
product);
PostAsJsonAsync automatically serializes the object.
Adding Request Headers
Many APIs require authentication headers.
client.DefaultRequestHeaders
.Add(
"Authorization",
"Bearer YOUR_TOKEN");
Authorization tokens are commonly used for secure API access.
Working with API Keys
client.DefaultRequestHeaders
.Add(
"X-Api-Key",
"YOUR_API_KEY");
Store API keys securely in configuration files or secret managers.
Error Handling
Network failures and API errors can occur unexpectedly.
try
{
var response =
await client.GetAsync(url);
response.EnsureSuccessStatusCode();
}
catch(HttpRequestException ex)
{
Console.WriteLine(ex.Message);
}
Proper error handling improves reliability and user experience.
Using Typed Clients
Typed clients provide a clean way to organize API communication.
builder.Services.AddHttpClient
<WeatherService>();
This approach improves maintainability and testability.
Dependency Injection Benefits
- Centralized configuration
- Improved testing
- Better maintainability
- Reusable services
- Cleaner architecture
Common Beginner Mistakes
- Creating a new HttpClient for every request.
- Ignoring response status codes.
- Hardcoding API keys.
- Not handling exceptions.
- Ignoring request timeouts.
- Not validating API responses.
Best Practices
- Use HttpClientFactory.
- Store secrets securely.
- Handle API failures gracefully.
- Use strongly typed models.
- Validate response data.
- Implement logging.
- Configure timeouts appropriately.
Frequently Asked Questions
What is HttpClientFactory?
HttpClientFactory is a built-in ASP.NET Core feature that manages HttpClient instances efficiently and improves performance.
Should I reuse HttpClient?
Yes. Reusing HttpClient prevents resource exhaustion and is considered a best practice.
Can ASP.NET Core consume REST APIs?
Absolutely. ASP.NET Core is commonly used to integrate with REST APIs, cloud services, and third-party platforms.
How do I secure API keys?
Store API keys in configuration files, user secrets, environment variables, or secure secret management systems.
Related Tutorials
- Using HttpClient in C#
- Build a REST API in ASP.NET Core
- Reading JSON in C#
- Dependency Injection in ASP.NET Core
- JWT Authentication in ASP.NET Core
- File Handling in ASP.NET Core
Conclusion
Consuming external APIs is a fundamental skill for modern ASP.NET Core developers. Whether you're integrating payment systems, weather services, cloud platforms, or business applications, reliable API communication is essential.
By understanding HttpClient, HttpClientFactory, JSON processing, authentication, error handling, and dependency injection, you can build secure, scalable, and maintainable integrations with external services.