Consuming a REST API in C# WPF

When consuming REST APIs in C# I like to use the Newtonsoft.Json library which is available as a NuGet package.

Start by adding the package to your library. Right-click on your project in the Solution Explorer (if using Visual Studio) and click on “Manage NuGet Packages…”

Search for Json and add Newtonsoft.Json.

Add a reference by typing using Newtonsoft.Json.Linq;

For connecting to the API you can use many options. To keep it simple we’ll use System.Net.WebClient. Ref example code below:

var apiUrl = "https://example.com/api/v1/helloworld";
using WebClient wc = new WebClient();
var jsondata = wc.DownloadString(apiUrl);
JArray jsonarray = JArray.Parse(jsondata);
foreach (var item in jsonarray)
{
    JObject jsonobject = JObject.Parse(item.ToString());
    Debug.WriteLine(jsonobject);
}

Another example without looping through the items and using WebClient in another way:

var apiUrl = "https://example.com/api/v1/helloworld";
using (WebClient wc = new WebClient())
{
    var jsondata = wc.DownloadString(apiUrl);
    JObject jsonobject = JObject.Parse(jsondata.ToString());
    Debug.WriteLine(jsonobject);
}