Mastering .NET MAUI APIs: Building a .NET MAUI Weather App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Welcome. In this video we are going to develop  a .NET MAUI weather app and explore the exciting part of Dotnet MAUI development, which is API  integration. This is a must watch video as we will explore the essential tips of implementing  APIs correctly and highlight common mistakes that can significantly affect your app's  performance. So, get ready for an immersive journey into the secrets of successful app  development. Let's dive right in. [Music] As we continue our app development journey, let's  dive deeper into the WeatherStack API and its various features. In our app we are utilizing the  API provided by weatherstack. You can find the link to their website in the video description. Click on  the link to open the website and explore the rich offerings they provide. To access the weatherstack  API, you will need to sign up for a new account to obtain your unique API key. It's a simple process  that grants you the access to their services and allows you to make the API calls. When you visit  the website, you'll notice that the weather stack mentions their valued customers who have  benefited from their API. It's inspiring to see how their services have made a positive impact on  a wide range of users. As you navigate through the website, you'll discover the different types of  API methods available. These methods allow you to retrieve specific weather information based  on your needs. WeatherStack provides sample responses of the current weather API giving you  a glimpse of the data you can expect to receive. Now let's take a look at the weather history  API. When you consume this API, you'll receive a response that contains historical weather data.  This information can be invaluable for various applications and analysis purposes. Additionally,  weather stack offers the weather forecast API which provides detailed weather predictions  for specific locations. By utilizing this API, you can retrieve accurate and up to date weather  forecasts. On the home page of the weather stack website, you will find some basic details about  their services and offerings. However let's take a moment to explore their pricing details. It's  important to note that the pricing information I am sharing with you right now is accurate at  the time of recording this video. However, do keep in mind that there might be changes when you  check their website. Always refer to the latest information available to make informed decisions.  Now let's move on to to the documentation page. Here you will find detailed documentation of the  API methods. When implementing a third-party API, it's crucial to go through the documentation  to gain a comprehensive understanding of the available methods and their usages. Within  the documentation weatherstack also mentions the error codes that you may encounter when making  API calls. Familiarizing yourself with these error codes will help you troubleshoot and handle any  issues effectively. Furthermore, the documentation highlights various API features, providing insight  into the specific details you can receive in the API response. This knowledge will empower you to  retrieve the necessary weather data for your app with precision. The documentation also covers  specific API details such as the historical weather API and the weather forecast API. These  sections provide information how to utilize these apis effectively to access past and future  weather data. Under the general options section, you will find the different types of query values  that you can send to the API. The first option is providing a location name where you can simply  send the name of the location and receive relevant weather information. Another option is providing  the ZIP code specifically for countries like the US, Canada and the UK. If you have coordinates  available, you can provide them as input to obtain precise weather data. WeatherStack also offers  the option to retrieve weather information based on the IP address. Additionally, you can use  the "fetch:IP" option which automatically identifies the device IP address location and  provides the weather information accordingly. Further down the documentation, you will find the  details about units and languages supported by the API. This allows you to customize the data  you receive according to your preferred units and language settings. For our specific application,  we need to fetch the current weather information by providing coordinates. This will ensure that we  receive real-time weather data for the location of interest. Now that we have a clear understanding  of the weather stack API and its features, let's proceed with the development of our .net maui  weather app. To begin, I have created a new .NET Maui app project. Before we dive into the project, I  want to mention that this video is part of our .NET MAUI tutorial series. If you are interested  in exploring more tutorials and expanding your knowledge you can find the playlist link in the  video description. Now let's focus on developing our project. First we'll add a folder named "Pages"  inside our project. This will help organize our app's content. Within the pages folder, I am  adding a new content page and naming it "WeatherInfoPage". This page will serve as the main content  area for displaying weather information. Moving on, we'll navigate to the app.xaml.cs class and assign  the newly created content page as the main page of our application. This ensures that the WeatherInfoPage will be the initial page displayed to the user. Now let's clean up the content page.  We can remove the auto created label inside the vertical stack layout as we won't be needing it.  To enhance the page appearance, I am assigning a title and a background color to the content page.  This will give it a more polished and cohesive look. Next, we'll focus on the user input section.  We'll place entry fields inside a frame for the user to enter the coordinates. To ensure proper  alignment, we'll utilize the grid control. Inside the grid, we'll add an entry field for latitude and  another one for longitude. These input fields will allow users to enter the specific coordinates they  want to retrieve whether information for. Moving on, we'll place a button below the entry fields.  This button will serve as a trigger to fetch the weather details from the API. Once we receive the  weather data from the API we can display it below. We'll start by placing an image control to display  an image related to the weather. This image URL will be obtained from the API response. Following  that, we'll add a label to display the temperature. The actual text for the temperature will be  updated later based on the API data. Additionally, we'll include another label to display a brief  description of the weather, providing users with an overview of the current conditions. To present  the location details, we'll add another label below the weather description label. Moving further down,  we'll include additional values like humidity and cloud cover level. To ensure proper alignment, we'll  utilize the grid control once again. Within a frame we'll display the humidity value. In another  frame we'll present the cloud cover level. This value will be represented as a percentage. Lastly  we'll use another frame to display whether it is currently day or night, indicated by a yes or no  value. With this design in place, we are ready to run the project and observe the app's appearance  in the emulator. In the emulator you can see that, we have entry fields for latitude and longitude  along with a button to initiate the weather information retrieval. The design also includes  sections to display various information obtained from the API. Our design is now complete providing  a user-friendly interface to input coordinates and view corresponding weather details. The next step  is to create a view model for the content page. We have already discussed view model implementation  in detail in our previous video. So feel free to refer back to that for a deeper understanding. To  keep our project organized, let's create a folder named "Models", within the project. In the models  folder, we'll create another folder named "ViewModels". This will help us maintain a structured  project layout. Now, let's proceed to create a class named "WeatherInfoPageViewModel" within the view  models folder. But before we proceed, it's necessary to install the "CommunityToolkit.Mvvm" library from  Nuget Packages. Here you can see the library at the top of the list. Upon installation, we can  continue by making our class a partial class. This is important because CommunityToolkit.Mvvm  Library also create classes with the same name. Next, let's create the necessary properties for  out view model. We'll start by creating properties for the latitude and longitude which we'll use  to search for weether data. To ensure seamless data binding, we can provide "ObservableProperty"  attribute for these properties. At this point, you may notice an error being displayed. This error  occurs because we haven't inherited the class from the "ObservableObject" class provided by the  CommunityToolkit.Mvvm Library. This class is essential for proper data binding functionality.  Moving on, we'll create additional properties for the weather icon, temperature, weather description,  location, humidity, cloud cover level and whether it is day or night. These properties will store  the retrieved weather information. In addition to the properties, we'll also create a method to fetch  the weather information from the API. To bind this method to the buttons command property, we should  provide the "RelayCommand" attribute. This ensures that when the button is clicked, the associated  method in the view model will be triggered. Now let's proceed with binding the ViewModel values  to the corresponding controls in the xaml file. First, we'll import the namespace of the viewmodel  class into the xaml file. This will allow us to access the view model within the xaml file. Then  we'll specify the data type of the content page to be the viewmodel class. This establishes  the connection between the view model and the content page. To enable data binding we'll  bind the latitude property to the first entry control and the longitude property to the second  entry control. This allows the user's input to be captured and stored in the view model. For the  buttons command property, will bind it to the FetchWheatherInformationCommand, we created  earlier. This ensures that when the button is clicked the associated method in the view model  will be executed. We'll continue by binding the remaining properties to their respective controls.  This includes weather icon, temperature, weather description, location, humidity, cloud cover  level and whether it is day or night. With these data bindings in place a view model is now  connected to the user interface enabling seamless updates and interactions. Before we proceed with  implementing the API, let's take a moment to test it using Postman. Postman is a powerful tool  that allows us to interact with the APIs and analyze their responses. To begin, I'll create a new  request in Postman. Since we are fetching current weather information, the request type will be get  as this API method follows the get protocol. I'll provide the API base URL in the request. The  specific API method we'll be using is called "current". As mentioned in the API documentation, we  need to pass a parameter named query as a query string. For this parameter, we'll provide the  coordinates separated by a comma as specified in the API documentation. The next parameter  we need to include is the access key, which we obtain after signing up for a new account on  weather stack website. For testing purposes I'll use my own access key as the parameter value. Now  let's send the request and observe the response. As you can see, we have successfully received  a response from the API. Within the response, we have valuable information. For instance, there is  an image URL mentioned as the weather icon. This URL can be used to display relevant weather icons  in our application. Additionally, we have access to the location information, providing us with the  specific details about the retrieved weather data. To streamline our development process, I'll copy  the entire response content from Postman. This content will be instrumental in creating a model class  that allows us to effectively map and utilize the retrieved weather data within our application.  In our project, I'll create a new folder called "ApiModel" inside the models folder. This folder will  house the classes related to the API response models. Next, I'll create a class named weather API  response within the API models folder. To simplify this process, I'll utilize a feature in Visual  Studio. I'll place the cursor below our class, open the edit menu and select paste special. From  there, I'll choose "Paste Json as classes". Visual Studio will automatically generate the required  classes based on the Json structure we copied from Postman. To align with naming conventions,  I'll modify the class names ensuring that they all start with WeatherApiResponse. Additionally,  I'll include the Json property name attribute for each property. This attribute allows us to assign  custom names for the properties, while ensuring the correct names are used during serialization  or deserialization of Json data. I'll make the necessary adjustments for the remaining properties  as well. With our model class setup, let's create a class named constants within our project. In  this class, we'll define important constants related to the API integration. We'll create a  string constant to hold our API key and another constant for API base URL. You can provide your  API key in the appropriate constant. Moving on, I'll create a folder named services within  our project. Inside this folder, I'll create a class named weather API service. This class  will handle the API calls and integration. To ensure a proper implementation, I'll declare  the HTTP client object as read-only. Then inside the Constructor, we can initiate the HTTP client  object. It's crucial to note that one of the best practices when working with HTTP client is to  instantiate it once and reuse it throughout the application's lifespan. Creating new instances for  each API call can lead to performance issues. Next, I'll assign the base address of the HTTP client  using the constant we defined for the API base URL. Now let's implement the method responsible for  fetching the weather information. This method named "GetWeatherInformation" will return the weather  API response object as a result. It accepts two parameters, latitude and longitude. Both of which  are strings, since we need to provide these values in the URL. Before making the API call, we'll check  if the device has an internet connection. If there is no internet, will return null. Otherwise we'll  proceed with the API call and return the object generated from the Json result. Now let's navigate  to the View model class and implement the fetch weather information method. But before that, we'll  declare the weather API Service as read-only and instantiate it within the Constructor. Within  the fetch weather information method, we'll call the service method to retrieve the weather  API response object. Afterward, we'll check if the object is not null, indicating a successful  API call. If it is not null, we can assign the values for our view model properties accordingly. For example, we can extract the first element from the weather icon array and assign it to the  corresponding view model property. Similarly, we'll set the temperature, location, weather description,  humidity, cloud cover level and whether it is day or night. Now let's run the application and  encounter the error we expect while calling the API. I'll provide the coordinates and click  the fetch Button. As anticipated, we received an error message stating, clear text HTTP traffic to  the URL is not permitted. This occurs because our API URL uses HTTP and starting from Android  9 there are restrictions on clear text or unencrypted HTTP traffic by default. To resolve  this we have two options, either switch to https URL, that is the preferred method. Or allow clear  text HTTP traffic in our application. Allow me to demonstrate how to enable clear text HTTP traffic.  Let's navigate to the platforms folder, expand the Android folder and open the Android manifest.xml  file. In the application tag we can set the value for "android:usesClearTextTraffic" to true.  Now let's run the project again. As I provide the coordinates as before and click the fetch button,  we can see that that the data is successfully populated in the content page. It displays values  such as temperature, location, humidity and more. Let's experiment with different coordinates. As  I do so, the displayed data updates accordingly. This demonstrates that our app is capable of  effectively consuming the API and retrieving the desired weather information. And that concludes  our tutorial on developing a weather app using .net MAUI and API integration. You have learned  valuable skills for building powerful apps. Stay tuned for more exciting tutorials in our dotnet  MAUI series. Don't forget to like, share and subscribe for future updates. Remember this  is just the beginning. The possibilities are endless when it comes to enhancing your app's  functionality and user experience. Don't forget to check out the other videos in our .net  MAUI tutorial series by clicking the playlist link in the video description. Happy  Coding and see you in the next video!
Info
Channel: Coding Droplets
Views: 3,368
Rating: undefined out of 5
Keywords: .net maui weather app, maui weather app, dotnet maui weather app, .net maui weather app github, best maui weather app, dotnet maui getting started, dotnet maui api, maui api client, .net maui apis, maui api call, maui api documentation, maui login using web api, .net maui web api call, .net maui clear text traffic, call web api from .net maui, consume web api in .net maui, .net maui rest api mvvm example, maui httpclient, c# maui httpclient, .net maui httpclient android
Id: zO2MfIjopUg
Channel Id: undefined
Length: 19min 57sec (1197 seconds)
Published: Mon Jul 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.