How to consume a RESTful API in C#

As a developer you will find yourself in need to consume complex RESTful API as you move forward in your career, so understanding a very basic on might help you get a step ahead. In this short post I will take the opportunity to share how to use the HttpClient class to consume RESTFUL APIs in a C# projects.

What is RESTful API?

Before I proceed into coding, I figured it would be best to describe briefly what exactly is a RESTful API, especially if you just started in web development.
I will try to keep it as simple as possible, so a RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. For instance, most of the services provided by companies such as Google, Facebook, Twitter have their own API which they expose to other third party companies to get information.

HttpClient Class


HttpClient provides a flexible and extensible API for accessing things exposed through HTTP, which fits perfectly a RESTful API.
Make sure to avoid coding your httpClient call as followed, because you run the risk of having System.Net.Sockets.SocketException due to the connection that is being disposed.


using(var client = new HttpClient())
{
}

Make sure to create a single instance of HttpClient in your program since that will help reduce waste of sockets.

Below is a simple console application I’ve put together to read data out of a RESTFUL API for managing a list of country data, such as capital, language, flag image, and currencies which you can download from github and test it yourself.


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web;

namespace ReadCountryData
{
class Program
{
public class Currency
{
public string Code { get; set; }

public string Name { get; set; }

public string Symbol { get; set; }
}

public class Country
{
public List Currencies { get; set; }

public string Name { get; set; }

public string Capital { get; set; }
}

static void Main(string[] args)
{
HttpClient http = new HttpClient();

string baseUrl = "https://restcountries.eu/rest/v2/name/";

string queryFilter = "?fields=name;capital;currencies";

Console.WriteLine("Enter your country name:");

string searchTerm = Console.ReadLine();

string url = baseUrl + searchTerm + queryFilter;

HttpResponseMessage response = http.GetAsync(new Uri(url)).Result;

string responseBody = response.Content.ReadAsStringAsync().Result;

var countries = JsonConvert.DeserializeObject>(responseBody);

PrintCountryInfo(countries);
}

public static void PrintCountryInfo(List countries)
{
int counter = 0;

foreach (var country in countries)
{
counter++;

Console.WriteLine("#" + counter);

Console.WriteLine("Country Name:" + country.Name);

Console.WriteLine("Country Capital:" + country.Capital);

foreach (var currency in country.Currencies)
{
Console.WriteLine("Country Currency:" + currency.Name);

Console.WriteLine("Country Code:" + currency.Code);

Console.WriteLine("Country Symbol:" + currency.Symbol);
}

Console.WriteLine(".......................................................");
}
Console.ReadKey();

}
}
}

So, I hope this post help clear some of doubts you had when it comes to consuming a simple RESTful API in C#.

Testing a resful Web API Using Postman

Recently I have worked on how to create a simple Web API service to manage a list of country capitals. I thought it would be beneficial to some if I put together a quick post to show how to test it using postman.

What is Postman?
Postman is a free API debugging tool which makes working with APIs faster and a bit easier. If you don’t already have it installed, feel free to download it so you can follow along.

How do you get Postman?
Postman is free and you can download it at “https://www.getpostman.com/“. Simple download it and following the instructions for the installation. After successful installation, open it and select HTTP Method and enter the URL of the Web API as shown below.

We’ll test the following commands:

[one_third]

HTTP Verbs

GET

GET

POST

PUT

DELETE

[/one_third]

[one_third]

URL/Endpoints

API/Countries

API/Countries/{id}

API/Countries

API/Countries/{id}

API/Countries/{id}

[/one_third]

[one_third_last]

Description

Get all countries

Get a specific country by ID

Add a new country

Update an existing country

Delete a country

[/one_third_last]


POST API/Countries

Let’s add a few countries to the list.

{
"name": "Afghanistan",
"capital":"Kabul"

}

GET API/Countries

I have submitted 6 countries. Let’s get the list of countries that were submitted using the GET verb in Postman.

GET API/Countries/{id}

To find a specific country I need to fetch it by sending the ID in the URL. See below for more.

PUT API/Countries/{id}

Let say I want to change the first country information because of an typo or maybe I just want to change it to a whole different country.
I need to send a PUT to do so.

Let’s verify to see if the first country in the list has been changed.

DELETE API/Countries/{id}

Now let’s try the delete to see what happens.

After deleting country 1, 2, 3,and 4 we now have 2 countries left.