Welcome to the OpenWeatherAPI repository! This project demonstrates how to call a third-party API (OpenWeather API in this case) using the three approaches of IHttpClientFactory
in .NET: simple/classic, named, and typed clients.
- IHttpClientFactory: Use the factory to manage
HttpClient
instances effectively. - Three Approaches: Learn the basic/classic
IHttpClientFactory
client in controller, the "named" HTTP client, and the "typed" HTTP client. - OpenWeather API Integration: Fetch weather data using the OpenWeather API.
I have written a Medium article on this topic: Use IHttpClientFactory Right Way!. In this article, I discuss the benefits of using IHttpClientFactory
, the problems it solves (e.g., socket exhaustion), and the three approaches to use HttpClient
with code examples just like in this repository.
-
Clone the repository
git clone https://github.com/zeecorleone/OpenWeatherAPI.git cd OpenWeatherAPI
-
Restore dependencies
dotnet restore
-
Set up your OpenWeather API key
- Set your OpenWeather API Key in environment variable named
OPENWEATHER_API_KEY
- Set your OpenWeather API Key in environment variable named
-
Run the application
dotnet run
Once the application is running, you can use endpoints (mentioned below) to fetch weather data from the OpenWeather API.
- Without Using HttpClientFactory:
https://localhost:7272/weatherforecast/GetOpenWeather
- Using HttpClientFacotry (simple):
https://localhost:7272/weatherforecast/GetOpenWeatherV1
- Using HttpClientFacotry (named):
https://localhost:7272/weatherforecast/GetOpenWeatherV2
- Using HttpClientFacotry (typed):
https://localhost:7272/weatherforecast/GetOpenWeatherV3
I plan to extend this example in future articles. Potential topics include:
- Handling third-party API call failures.
- Implementing retry policies.
Contributions are welcome! Please submit a pull request or open an issue to discuss what you would like to change.
This project is licensed under the MIT License. See the LICENSE file for more details.