What is UWP App Api and How to Use?
This article gives a brief introduction about the using APIs in UWP Apps.
Pre-requisite Knowledge
Before we start with the understanding of using APIs in UWP App, we should know-
Introduction of using APIs in UWP App
Let’s get started with the creation of this Application.
- Same old steps, Open Visual Studio (I’ll use VS 2019, Community Edition for this demo- It’s free)
- After opening Visual Studio, click on Create a New Project
- On the next screen, Search for “UWP” in the top given search bar and then select “Blank App (Universal Windows)”, then simply click on Next
- Give your project a name, then click on Next
- Here we can select the versions accordingly, but for this demo, I’m keeping it untouched.
- Now let’s create a basic front end for our API calling App.
Open MainPage.xaml for the Front End code.
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBox IsEnabled="False" Text="Check latitude and longitude" /> <TextBox x:Name="cityName" Text="Delhi" /> <Button Content="GetCoordinates" HorizontalAlignment="Center" Click="Button_Click"/> <TextBox x:Name="coordinatesTxtBox" Text="Coordinates Here" TextWrapping="Wrap" HorizontalAlignment="Center" Height="200" Width="600"/> </StackPanel>
- Include this header statement:
using System.Net.Http;
- Now let’s code the Button to fetch the Data from the Location API. We’ll use the Meta Weather API for the location. Double click on the Button to go to its triggered code. And then place the below code in it.
private async void Button_Click(object sender, RoutedEventArgs e)
private async void Button_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
string choiceSelected = cityName.Text.ToLower();
// Request parameters
var url = "https://www.metaweather.com/api/location/search/?query="+choiceSelected;
// Asynchronously call the REST API method.
var response = await client.GetAsync(url);
// Asynchronously get the JSON response.
string contentString = await response.Content.ReadAsStringAsync();
coordinatesTxtBox.Text = contentString;
client.Dispose();
}
- After placing the code, now let’s run the Application. So press F5 to run it.
Note that the result is just a plain JSON string, as the conversion of JSON to object is currently beyond the scope of this article. So we’ll review that part later in the near future
Conclusion - In this article, we have learned about:
- Hands-On APIs in our UWP Application