Wednesday, September 12, 2018

Call a REST API from .NET

To call a REST API using the "GET" ("POST" is beyond the scope of this article) HTTP verb, use the following code:

Using Client As New System.Net.WebClient

    Dim Results As String =
        Client.DownloadString("API URL")

End Using

This will populate the Results variable with the output of the web service call.  Almost invariably, this will be in the JSON format.  Note that all input is contained in query parameters in the API URL.

Now we need to get the JSON into a .NET object that can be easily read.  This process is called deserialization.  You can do this using native .NET classes, but oddly, Microsoft seems to prefer that you use the JSON.net library.  This can be downloaded at https://www.newtonsoft.com/json.

Next you will need to create a series of classes that correspond to the structure of the JSON output.  For example, if your output JSON looks like this:

{"query":{
    "count":1,
    "created":"2018-09-07T15:51:40Z",
    "lang":"en-US"
    }
}

You should create two classes like this:

Public Class Output
    Public Property Query As QueryDetails
End Class

Public Class QueryDetails
    Public Property Count As Integer
    Public Property Created As DateTime
    Public Property Lang As String
End Class

Then, simply write the following code to deserialize the JSON output into the .NET Output object:

Dim MyOutput As New Output
Newtonsoft.Json.JsonConvert.PopulateObject(Results, MyOutput)

No comments:

Post a Comment