In this post we will build a weather app using Python.
The Weather App Application we building can help is doing the following things:
- Fetching weather data from the internet: We will use a weather API (Application Programming Interface) to fetch weather data from the internet. There are many weather APIs available that allow us to access current and forecasted weather data for a specific location we will use here Oikolab.
- Accessing any specific location’s real-time weather data: Once we obtain an API key, we will use Python’s requests library to make HTTP requests to the API’s endpoints to access weather data for a specific location. We will need to pass the API key and the location’s latitude and longitude coordinates as parameters in the request. The API will return a JSON response with the current and forecasted weather data for the location.
Also,we will be using 3 simple concepts for creating the Weather App Application in Python:
1. APIs
2. JSON
3. Pandas
Below are the details of these concepts:
Application Programming Interface (APIs)
APIs (Application Programming Interfaces) are a way for different software systems to communicate with each other and exchange data. In the context of a weather application, an API allows the application to access weather data from a remote source (such as a weather service) and use that data to display the current and forecasted weather for a specific location.
JavaScript Object Notation (JSON)
JSON (JavaScript Object Notation) is a data interchange format that is commonly used in web APIs to transmit data between a server and a client. In the context of a weather application, JSON is often used to transmit weather data from a weather API to the application.
To use JSON in a weather application, you will need to:
- Make an API request: Use Python’s requests library to make an HTTP request to a weather API endpoint. The API will return a response in the form of a JSON string.
- Parse the JSON string: Use Python’s json library to parse the JSON string and convert it into a Python data structure, such as a dictionary or a list. The data structure will contain the weather data in a structured format that can be easily accessed and processed.
- Access and process the data: Use Python’s built-in functions and libraries (such as pandas and numpy) to access and process the data as needed. For example, you might want to extract specific weather data (such as the temperature or humidity) and perform calculations on it.
Pandas
Pandas is a powerful Python library for data analysis and manipulation. It can provide us with a range of tools and functions that we can use for working with weather data in a weather application.
We will use Pandas to load weather data from API which is a two-dimensional table of data with rows and columns. We will then use Pandas’ built-in functions and methods to manipulate and transform the data. For example, we will use Pandas to filter the data to select a specific time period or group the data by a specific attribute (such as temperature). We will also use Pandas to analyze and visualize data.
Creating an account with Oikolab
Please note: In order to query Oikolab Weather Database we need an API key, we can get an API key when we create an account with Oikolab. Below is how you can create an account at Oikolab.
Step 1: Go to https://oikolab.com/signup/ and fill in the details:
Step 2: Go to your email and click the confirmation link. It will lead you to this page:
Step 3: Enter your credentials and sign in:
Step 4: Go to subscriptions:
Step 5: Copy your API Key. This will be needed in the project:
Practical Session: Now we will start coding in our notebook!
import json import pandas as pd import requests |
The import statement in Python is used to import modules.
The import json statement imports the json module, which provides functions for working with JSON data. JSON (JavaScript Object Notation) is a lightweight data interchange format that is often used for exchanging data between a server and a web application
The import pandas as pd statement imports the pandas module and gives it an alias of pd.
The import requests statement imports the requests module, which provides functions for sending HTTP requests and receiving responses from web servers. This is used to access data from web APIs or to download files from the internet.
city = input() date = input() URL = ‘https://api.oikolab.com/weather’ OIKO_KEY = ‘Your Key’ |
The input() function is being used to get user input from the command line.
The first line of code, city = input(), prompts the user to enter a city and then stores the user’s input in a variable called city.
The second line of code, date = input(), prompts the user to enter a date and then stores the user’s input in a variable called date.
The third line of code defines a variable called URL that stores a string representing the URL of an API (Application Programming Interface) for getting weather data.
The fourth line of code defines a variable called OIKO_KEY that stores a string representing an API key for accessing the weather API.
resp = requests.get(URL, params = {‘param’: [‘temperature’], ‘start’: date, ‘location’: city, ‘end’: date, ‘api-key’: OIKO_KEY, } ) |
This code uses the requests library to make a GET request to the weather API specified in the URL variable. The params parameter is a dictionary that specifies the query parameters for the request.
The param key in the params dictionary specifies the type of weather data that is being requested from the API. In this case, the param value is [‘temperature’], so the request is asking for temperature data.
The start and end keys in the params dictionary specify the start and end dates for the requested weather data. The location key specifies the location for which the weather data is being requested.
Finally, the api-key key in the params dictionary specifies the API key that is required to access the weather API. This key is stored in the OIKO_KEY variable.
The requests.get() function sends the HTTP GET request to the API and returns a Response object that contains the server’s response to the request. This Response object is stored in the resp variable.
This is how your output will look like:
weather_data = resp.json() [‘data’] |
This code appears to be extracting the data from the data field of the JSON object that was returned in the HTTP response. The json() method is used to parse the response body as JSON, and the [‘data’] syntax is used to access the data field of the JSON object. The value of the data field is then assigned to the weather_data variable.
type(weather_data) |
The type() function is a built-in function in Python that returns the type of an object.
If you call type(weather_data), it will return the type of the object stored in the weather_data variable.
weather_data = json.loads(resp.json()[‘data’]) |
resp is an HTTP response object and json() is a method that is used to parse the response body as JSON. loads() is a function from the json module that is used to parse a JSON string into a Python object, such as a dictionary or list.
Here, JSON data is being extracted from the data field of the JSON object that was returned in the HTTP response, and then it is being passed to json.loads() to parse it into a Python object. This Python object is then we have assigned to the weather_data variable
df = pd.DataFrame(index=pd.to_datetime(weather_data[‘index’],unit=’s’), data=weather_data[‘data’], columns=weather_data[‘columns’]) |
Using the above code we have created Pandas DataFrame from the weather_data object. The pd.DataFrame() function takes a number of arguments to specify the data, index, and columns of the DataFrame.
In this case, the index argument is being set to the index field in the weather_data dictionary, which is being passed to the pd.to_datetime() function to convert it to a series of datetime objects. The unit=’s’ parameter specifies that the index field is in seconds.
The data argument is being set to the data field in the weather_data dictionary, which should contain the data for the DataFrame. The columns argument is being set to the columns field in the weather_data dictionary, which should contain the names of the columns for the DataFrame.
Once the DataFrame is created, it is being assigned to the df variable
df |
This code will create a DataFrame in the console or notebook.
This is how our output will look like:
temp = int(df.iloc[0,4]) |
It accesses the data in the DataFrame df and extracts the value in the first row and fourth column. The iloc attribute is used to access the data in the DataFrame by integer index.
The iloc[0, 4] syntax selects the data in the first row and fourth column of the DataFrame. The iloc attribute returns a Pandas Series object representing the row or column of data.
In this case, the value in the selected cell is being cast to an integer using the int() function and then assigned to the temp variable.
print(f”Temperature for {city} on {date} = {temp}C”) |
Above code appears to be using a formatted string to print a message to the console or notebook. The print() function is being passed a string that includes placeholders for values that will be filled in at runtime.
The string uses the f string syntax, which allows you to embed expressions inside curly braces {} and have them be evaluated as Python code. The expressions inside the curly braces are replaced with their values when the string is printed.
In this case, the string includes placeholders for the city, date, and temp variables. These variables are being accessed using the city, date, and temp names and their values will be used to fill in the placeholders in the string when it is printed.
This is how our output will look like based on city & date entered by user:
Congratulations!
We have created the Weather App in Python. Try other tutorials to acquire more skills.