Getting data from RESTful web services and other websites is really easy in VB.NET and can be done in just a few lines of code.
In this example we will get data from one of the APIs provided by Steam that returns the full list of apps available on the service.
Getting The Data
First of all, you will need a couple of Imports
statements.
1 2 |
Imports System.Net Imports System.IO |
Next, we need to create a WebRequest
for the data we want and keep track of the object so we can get the response when it’s available.
1 2 |
Dim req As HttpWebRequest = WebRequest.Create("http://api.steampowered.com/ISteamApps/GetAppList/v0002/") Dim res As HttpWebResponse = req.GetResponse() |
This code will create the request for the data we want and the get the response from the server and it will be stored in the res
object. To get the actual content of the response, we will need to retrieve the underlying stream from the response.
1 |
Dim sr As New StreamReader(res.GetResponseStream()) |
After this, we have a stream, sr
, that contains all the data returned from the server.
Using The Data
The response from this particular web service will be in JSON format so we will need to transform the data from a stream to something useful in order to extract the bits we want from it.
One of the easiest way to do this is using JSON.NET, an excellent open source library for working with JSON data. To use JSON.NET in this project, go to Nuget and add the one called ‘Newtonsoft.Json’ to the project. Then add another Imports
statement so we can access it.
1 |
Imports Newtonsoft.Json |
Now we can use the DeserializeObject
method from JSON.NET to take the contents of the stream and turn it into a generic Object
.
1 |
Dim AvailableApps As Object = JsonConvert.DeserializeObject(sr.ReadToEnd()) |
After this, AvailableApps
will contain all the data from the stream from which we can either directly grab the bits we want or can more broadly query using LINQ.
The Full Code
The Imports
.
1 2 3 |
Imports System.IO Imports System.Net Imports Newtonsoft.Json |
The data gathering code.
1 2 3 4 |
Dim req As HttpWebRequest = WebRequest.Create("http://api.steampowered.com/ISteamApps/GetAppList/v0002/") Dim res As HttpWebResponse = req.GetResponse() Dim sr As New StreamReader(res.GetResponseStream()) Dim AvailableApps As Object = JsonConvert.DeserializeObject(sr.ReadToEnd()) |
So in just four lines and a couple of Imports
we have got the data from the service and started to manipulate it so we can use it.