15 Oct 2019
In today’s world of interconnected apps & services, you may often need to call another API to get or modify information.
In this article I’d like to show you how to do the following:
Let’s get on with it!
This tutorial uses ASP.NET Core 3 MVC. If you are using a different version, some of the steps may need to be modified.
If you are starting from scratch, you can just create a new ASP.NET Core MVC project by running the following command:
where MyMvcApp
is the name for your new project. If you already have a project, ignore this step.
Given your app will be calling some remote API, you want to make sure that in case of a flaky
connection or a timeout it’s going to re-try to eventually get the data. That’s why you going to
need to add a reference to Microsoft.Extensions.Http.Polly
package. To read more about Polly and
re-try policies, check out this article: “Implement HTTP call retries with exponential backoff with
HttpClientFactory and Polly policies”
So, to add this package, run this command from your project folder (that’s where your .csproj
resides):
Also, you’ll need a Newtonsoft.Json package so that you could turn all this JSON into neat C# objects that are easier to work with. So go ahead and run this command to add it:
There are several approaches and classes you may use to call external APIs, and you might have come across
some of them already - classes like WebClient
or HttpClient
. While still working, they provide
quite manual and low-level access to APIs. However in web apps, since they may have several threads
running and calling different APIs, you want to let the application manage creation, re-use and
disposal of these resources.
That’s why one of the recommended practices at the moment is to use Http Client Factory pattern.
That is a standard part of .NET Core, and it takes good care of things like configuring
HttpClient
s, managing creation and disposal of them (to avoid socket exhaustion, that’s when OS
runs out of available network sockets) and does a few more things for you – see here for the
complete list.
Also, feel free to check out all the use cases of the Http Client Factory here – the class is easy to use and examples are quite clear.
You will also need Polly (the package you just installed above) to add retry policies.
Add the following code to the Startup.cs
file:
In this example we are going to use weather forecasting API from MetaWeather - it’s free and doesn’t need any API keys or other credentials, so should be easy to get working on your computer. Download complete, fully tested and working project for this article if you want to save yourself all the typing or if you run into any issues along the way.
OMG can’t believe we actually got here after all this setup! Bear with me, we’re really close, soon you’ll be getting that sweet JSON and displaying it!
First of all, you’ll need to create a class (or set of classes) to represent your JSON structures in C#. Luckily, there’s a web app for that! Head to http://json2csharp.com/, paste your expected JSON response in there, click ‘Generate’ and you’ll get your C# class(es).
I am going to use this MetaWeather API response to generate C# classes. Feel free to change the generated class names, however, do not change the field names, as those need to match your JSON.
In my case, I get something like this:
Now it’s time to call the API, and turn the response into an instance of that freshly created class. In one of your controllers, add the following code:
Things to pay particular attention to:
HttpClient
with the help of HttpCientFactory
result.IsSuccessfulStatusCode
needs to be checked before proceeding to retrieve the responseJsonConvert.DeserializeObject<WeatherForecast>()
call does all the magic of converting JSON
response in string form to C# class instanceNow is the easy bit – you already have your strongly-typed model, representing the JSON result, and you can render it to the user:
Which gives us something like this:
In this article, you have just learnt how to:
Download fully tested and 100% working Visual Studio solution with the source code used in this article for FREE – just enter your name and email in the form below, and I’ll send you the download link right away.
You will also get access to all the source code for all existing and new articles on the site, and access to my mailing list, which receives handy timesaving tips on .NET Core programming.