How to load weather data using VB.net

Visual Basic .NET (VB.NET) is a versatile, modern programming language developed by Microsoft. It is part of the .NET framework and is designed for building robust and scalable applications for Windows, web, mobile, and cloud platforms. (Note that although Microsoft dropped the .NET portion of the name some years ago, we will continue to use the term VB.NET here as that is its common name and is useful to differential this technology from old version of Visual Basic.) VB.NET inherits the syntax and principles of its predecessor, Visual Basic, while introducing significant enhancements and compatibility with the Common Language Runtime (CLR). Known for its simplicity and readability, VB.NET is particularly popular among developers for rapid application development. It supports object-oriented programming, structured programming, and event-driven programming paradigms, making it suitable for a wide range of application types. VB.NET is commonly used for developing graphical desktop applications and related software solutions within the Microsoft ecosystem. For these reasons, adding weather data as input to a VB.NET application often is a valuable addition to your VB.NET project.

In this article we will show how to load weather data into a VB.NET program using Visual Crossing’s Timeline API. While VB.NET has built-in support for both HTTP queries and JSON parsing, via System.Net.Http and System.Text.Json, Newtonsoft.Json is still a popular alternative for processing JSON. So, we’ll present the example using System.Text.Json and then discuss the changes required for Newstonsoft.

Sample Code

Imports System.Net.Http
Imports System.Text.Json

Module Module1

    Sub Main()
        ' Replace these values with your actual API key and location
        Dim apiKey As String = "YOUR_API_KEY"
        Dim location As String = "Leesburg, VA"
        Dim startDate As String = "2023-01-01"
        Dim endDate As String = "2023-01-07"

        ' Visual Crossing API endpoint
        Dim apiEndpoint As String = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/"

        ' Create an instance of HttpClient
        Using client As New HttpClient()
            ' Set up query parameters
            Dim queryParams As String = $"?key={apiKey}&location={location}&startDate={startDate}&endDate={endDate}"

            ' Make the API request
            Dim response As HttpResponseMessage = client.GetAsync($"{apiEndpoint}{queryParams}").Result

            ' Check if the request was successful (status code 200)
            If response.IsSuccessStatusCode Then
                ' Read and parse the JSON response using System.Text.Json
                Dim jsonResponse As String = response.Content.ReadAsStringAsync().Result
                Dim weatherData As WeatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonResponse)

                ' Print weather data
                Console.WriteLine("Weather data:")
                Console.WriteLine($"Date: {weatherData.Days(0).DatetimeStr}")
                Console.WriteLine($"Temperature: {weatherData.Days(0).Temp2m}°C")
                Console.WriteLine($"Precipitation: {weatherData.Days(0).Precipitation} mm")
            Else
                ' Print error message if the request was not successful
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}")
            End If
        End Using
    End Sub

End Module

' Define a class to represent the structure of the JSON response
Public Class WeatherResponse
    Public Property Days As List(Of WeatherDay)
End Class

Public Class WeatherDay
    Public Property DatetimeStr As String
    Public Property Temp2m As Double
    Public Property Precipitation As Double
    ' Add more properties as needed
End Class

(Before using this code directly, make sure to replace “YOUR_API_KEY” with your actual Visual Crossing API key.  You can obtain a free API key by signing up for a Visual Crossing Weather account.)

This example fetches the weather forecast for a given period (January 1, 2023 through January 7, 2023) for a specified location (Leesburg, VA).  You can adjust these parameters according to your specific requirements. For more information on how to do that, keep reading.

Understanding the sample

Let’s break this code sample down into sections, to better understand what it is doing in detail.

The first part of the code sets up our imports and defines the primary variables that we will need in the to make the query. These values include our API Key, the location of interest, the dates, and the HTTPS endpoint for the Visual Crossing Weather service.

Imports System.Net.Http
Imports System.Text.Json

Module Module1

    Sub Main()
        ' Replace these values with your actual API key and location
        Dim apiKey As String = "YOUR_API_KEY"
        Dim location As String = "Leesburg, VA"
        Dim startDate As String = "2023-01-01"
        Dim endDate As String = "2023-01-07"

        ' Visual Crossing API endpoint
        Dim apiEndpoint As String = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/"

The next section creates the instance of HttpClient that we will use to make the URL query. In order to make this query, however, we need to build the URL from our parameters. We do this by building the queryParams string containing the URL parameters and then making the HTTPS request to the Visual Crossing Weather server using the GetAsync call.

        ' Create an instance of HttpClient
        Using client As New HttpClient()
            ' Set up query parameters
            Dim queryParams As String = $"?key={apiKey}&location={location}&startDate={startDate}&endDate={endDate}"

            ' Make the API request
            Dim response As HttpResponseMessage = client.GetAsync($"{apiEndpoint}{queryParams}").Result

If the HTTPS request was successful, we parse the JSON into our custom class (described below) that holds the resultant weather data. We then print the date, temperature, and precipitation for the first day to the console as an example. Of course, a more useful program would likely use this weather data for additional processing or other useful task such as loading it into a database or making a graphical presentation to the user.

            ' Check if the request was successful (status code 200)
            If response.IsSuccessStatusCode Then
                ' Read and parse the JSON response using System.Text.Json
                Dim jsonResponse As String = response.Content.ReadAsStringAsync().Result
                Dim weatherData As WeatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonResponse)

                ' Print weather data
                Console.WriteLine("Weather data:")
                Console.WriteLine($"Date: {weatherData.Days(0).DatetimeStr}")
                Console.WriteLine($"Temperature: {weatherData.Days(0).Temp2m}°C")
                Console.WriteLine($"Precipitation: {weatherData.Days(0).Precipitation} mm")

The final section of our main code is a bit of simple error handling. If the HTTPS request fails, we print the status code and the reason description. A production version of this code would want to include better error handling that not just alerts the user in text, but also tries to recover. However, for the sake of this example, we’ve only included the most basic error handling, however.

            Else
                ' Print error message if the request was not successful
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}")
            End If
        End Using
    End Sub

End Module

The final part of our code defines the structures into which the weather response JSON will be parsed. In this case, the WeatherResponse is made of a list of WeatherDay objects. Each WeatherDay stores the date, temperature, and precipitation for a given day in the response. In the case of this simple example, we only store those three values from the results since those are the only values this sample uses. However, in production code, we would almost certainly want to store and use more weather elements from the response. Luckily, this is easy to do simply by extending our structure. The JSON parser takes care of the rest.

' Define a class to represent the structure of the JSON response
Public Class WeatherResponse
    Public Property Days As List(Of WeatherDay)
End Class

Public Class WeatherDay
    Public Property DatetimeStr As String
    Public Property Temp2m As Double
    Public Property Precipitation As Double
    ' Add more properties as needed
End Class

Finally, we’ll add a quick discussion of how you would change the code if you wanted to use Newtonsoft’s JSON parser instead. Luckily the changes are rather simple. In addition to the obvious “Imports” change, instead of using System.Text.Json you would simply let Newtonsoft parse the JSON results into a JObject. From there we could pick up the specific elements needed using the SelectToken method. The code below would be a drop-in replacement for the response parsing and printing code described above. In short, whatever VB.net JSON parsing library you prefer, working with weather data is easy.

            ' Check if the request was successful (status code 200)            
            If response.IsSuccessStatusCode Then
                ' Read and parse the JSON response
                Dim jsonResponse As String = response.Content.ReadAsStringAsync().Result
                Dim weatherData As JObject = JObject.Parse(jsonResponse)

                ' Print weather data
                Console.WriteLine("Weather data:")
                Console.WriteLine($"Date: {weatherData.SelectToken("days[0].datetimeStr")}")
                Console.WriteLine($"Temperature: {weatherData.SelectToken("days[0].temp2m")}°C")
                Console.WriteLine($"Precipitation: {weatherData.SelectToken("days[0].precip")} mm")

In summary, this is just a sample that has been simplified to show the basic flow of querying data and parsing Visual Crossing Weather JSON results in VB.net.  Obviously, production code would be more careful in handling error cases and more flexible in the data being queried.  However, this sample should give any VB.net coder a good starting point to use when developing your own VB.net weather applications.

Questions or need help?

If you have a question or need help, please post on our actively monitored forum for the fastest replies. You can also contact us via our support site or drop us an email at support@visualcrossing.com.