Now you know to call a Web API and it's easy to do so

Ryan Chong
CERTIFIED EXPERT
The best way to learn is to teach
Published:
Edited by: Andrew Leniart
Calling Web API to grab data is pretty common for system integration. In fact, this is the current system development trend where we can see complex systems are tend to be developed in a small scale and distributed into smaller systems.
Calling Web API to grab data is pretty common for system integration. In fact, this is the current system development trend where we can see complex systems tend to be developed on a small scale and distributed into smaller systems. These smaller systems provided the necessary interfaces for the integrations. Web API is commonly being referred to provide such services for the web requests.

Inspired by a new member's first question: Window Forms, VB.net, API, Full Example, I would like to demonstrate on how we could call a Web API pretty easy in .NET programming, whether it's in VB.NET or C#. For this article, I would do it in VB.NET.

I would like to share the steps of my development below:

1) Decide what Web API to be used
2) Call the Web API
3) Integrate the result into the form
4) The final outcome



1) Decide what Web API to be used

The original question was asking if we could pulling weather data from some Web API. However, in this article, I would like to try out something different.

The Web API I would prefer is from Postman, which provided the data relating to COVID-19.

https://covid19api.com/


We could find more documentation at: https://documenter.getpostman.com/view/10808728/SzS8rjbc

2) Call the Web API

The Web API portal makes it simple, so a simple GET request that without authentication can be called to pull out the data.

The data being returned is in JSON format.

And for certain programming languages, sample codes are provided.


For this article, I would probably:
  • Add a country drop-down list and populate the list by calling "Countries" Web API  (https://api.covid19api.com/countries)

    The sample code would be:

    Public Function LoadCountry() As List(Of Country)
    
            Try
                'Grab the data from Web API
                Dim webClient As WebClient = New WebClient()
                Dim URL As String = "https://api.covid19api.com/countries"
                Dim json As String = webClient.DownloadString(New Uri(URL))
                Dim obj = JsonConvert.DeserializeObject(Of List(Of Country))(json)
    
                'Add a blank item
                Dim blank As New Country
                blank.Country = ""
                blank.ISO2 = ""
                blank.Slug = ""
                obj.Add(blank)
    
                'Sort the list
                LoadCountry = obj.OrderBy(Function(x) x.Country).ToList()
            Catch ex As Exception
                LoadCountry = Nothing
            End Try
    
        End Function

    Class definition:

    Public Class Country
        Public Property Country As String
        Public Property Slug As String
        Public Property ISO2 As String
    End Class

  • Add a DateTimePicker control to select the date
  • Add a button to retrieve the data by calling "By Country All Status" Web API (https://api.covid19api.com/country/<COUNTRY>?from=<STARTDATE>&to=<ENDATE>)

    The sample code would be:

    Public Function LoadCountryStatus(Ctry As String, Dt As Date) As CountryStatus
    
            Try
                'Grab the data from Web API
                Dim webClient As WebClient = New WebClient()
                Dim URL As String = "https://api.covid19api.com/country/" & Ctry & "?from=" & Format(Dt, "yyyy-MM-dd") & "T00:00:00Z&to=" & Format(Dt, "yyyy-MM-dd") & "T00:00:00Z"
                Dim json As String = webClient.DownloadString(New Uri(URL))
                Dim obj = JsonConvert.DeserializeObject(Of List(Of CountryStatus))(json)
    
                'Find the exact date's data
                LoadCountryStatus = obj.Find(Function(p) p.Date = Dt.Date)
            Catch ex As Exception
                LoadCountryStatus = Nothing
            End Try
    
        End Function

    Class definition:

    Public Class CountryStatus
        Public Property ID As String
        Public Property Country As String
        Public Property CountryCode As String
        Public Property Province As String
        Public Property City As String
        Public Property CityCode As String
        Public Property Lat As String
        Public Property Lon As String
        Public Property Confirmed As Integer
        Public Property Deaths As Integer
        Public Property Recovered As Integer
        Public Property Active As Integer
        Public Property [Date] As Date
    End Class

3) Integrate the result into the form

We could design the form in the way we wanted, but for this illustration, the form would be presented like this:


So now, we can put all the codes in the form:

In the Form Load event:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'Binding
        cbCountry.DataSource = COVID19.LoadCountry()
        cbCountry.DisplayMember = "Country"
        cbCountry.ValueMember = "Slug"

        'Pre-select the Country I staying with
        cbCountry.SelectedIndex = cbCountry.FindString("singapore")

        'Trigger to get the data
        btnGetData_Click(sender, e)
    End Sub

In the Get Data button's Click event:

Private Sub btnGetData_Click(sender As Object, e As EventArgs) Handles btnGetData.Click

        'Something wrong with Web API? No data being populated
        If cbCountry.Items.Count = 0 Then
            Exit Sub
        End If

        'Simple validation to make sure a Country is selected
        If cbCountry.SelectedValue = "" Then
            MessageBox.Show("Please select a Country", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If

        'Get the expected data
        Dim d As CountryStatus = COVID19.LoadCountryStatus(cbCountry.SelectedValue, dtDate.Value)

        'Display the expected data
        If d Is Nothing Then
            lblConfirmed.Text = "Data not available"
            lblDeaths.Text = "Data not available"
            lblRecovered.Text = "Data not available"
            lblActive.Text = "Data not available"
        Else
            lblConfirmed.Text = d.Confirmed.ToString
            lblDeaths.Text = d.Deaths.ToString
            lblRecovered.Text = d.Recovered.ToString
            lblActive.Text = d.Active.ToString
        End If
    End Sub

Before we go to the next step, just to share the full codes for the Class definitions:

Imports System.Net
Imports Newtonsoft.Json

Module COVID19
    Public Function LoadCountry() As List(Of Country)

        Try
            'Grab the data from Web API
            Dim webClient As WebClient = New WebClient()
            Dim URL As String = "https://api.covid19api.com/countries"
            Dim json As String = webClient.DownloadString(New Uri(URL))
            Dim obj = JsonConvert.DeserializeObject(Of List(Of Country))(json)

            'Add a blank item
            Dim blank As New Country
            blank.Country = ""
            blank.ISO2 = ""
            blank.Slug = ""
            obj.Add(blank)

            'Sort the list
            LoadCountry = obj.OrderBy(Function(x) x.Country).ToList()
        Catch ex As Exception
            LoadCountry = Nothing
        End Try

    End Function

    Public Function LoadCountryStatus(Ctry As String, Dt As Date) As CountryStatus

        Try
            'Grab the data from Web API
            Dim webClient As WebClient = New WebClient()
            Dim URL As String = "https://api.covid19api.com/country/" & Ctry & "?from=" & Format(Dt, "yyyy-MM-dd") & "T00:00:00Z&to=" & Format(Dt, "yyyy-MM-dd") & "T00:00:00Z"
            Dim json As String = webClient.DownloadString(New Uri(URL))
            Dim obj = JsonConvert.DeserializeObject(Of List(Of CountryStatus))(json)

            'Find the exact date's data
            LoadCountryStatus = obj.Find(Function(p) p.Date = Dt.Date)
        Catch ex As Exception
            LoadCountryStatus = Nothing
        End Try

    End Function
End Module

Public Class Country
    Public Property Country As String
    Public Property Slug As String
    Public Property ISO2 As String
End Class

Public Class CountryStatus
    Public Property ID As String
    Public Property Country As String
    Public Property CountryCode As String
    Public Property Province As String
    Public Property City As String
    Public Property CityCode As String
    Public Property Lat As String
    Public Property Lon As String
    Public Property Confirmed As Integer
    Public Property Deaths As Integer
    Public Property Recovered As Integer
    Public Property Active As Integer
    Public Property [Date] As Date
End Class

4) The final outcome

VoilĂ ! and here's the outcome from what we have completed.



What you could do next is play around with the interface by changing the Country and Date, and see if the numbers are currently refreshed.



The Summary

So now it's toward the end of this article, but I just want to emphasize that's how easy it is for such Web API integration to happen with minimum programming experience. However, when we are dealing with Web API (or rather we usually called as Web Requests), we need to know how to debugging. And Postman no doubt is one of the great tools we could use for this purpose.

I hope you enjoy to read this article and giving me feedback when it's available.
1
1,106 Views
Ryan Chong
CERTIFIED EXPERT
The best way to learn is to teach

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.