In this tutorial, we will build a simple weather web application using Python and Django. It will show current weather conditions in a certain city. We will also use ClimaCell Weather API to get weather data for our application.
To obtain access to the ClimaCell API, you first need to sign up on RapidAPI. Next, subscribe to the pricing plan, and that’s it. Now you are able to make a request to the ClimaCell API. For this tutorial, using a free Basic plan will be sufficient.
You can test ClimaCell API directly in the browser on the RapidAPI site. This functionality also provides a code snippet with a query to the API in many programming languages.
You can also see what the data sent by the API looks like. Click “Test Endpoint” and go to bookmark “Results”.
ClimaCell API can provide data in the following different time frames:
We are interested in Realtime weather conditions. From the documentation of the ClimaCell API, we can find out what data we can get in the Realtime option. For our weather app, we will get weather conditions, temperature, wind speed, and the type of precipitation.
To begin the project you can start a virtual environment named, for example, Django_web. Change the directory to “Django_web” in your terminal or command line. Then install Django and a couple of other dependencies, that we will use in this project, by running the next command:
pipenv install django requests pandas
The next step is creating a Django project called WeatherSite.
django-admin startproject WeatherSite
After that, Django will create a WeatherSite folder with some other folders and Python files. Now we can run the server and check whether it works. Navigate to a WeatherSite directory and run the command:
python manage.py runserver
Look at the terminal and view the URL for your web application. By default it is 127.0.0.1:8000.
Go to that URL in your browser.
If you see this page, it means that you did everything right.
In general, a Django project consists of several apps. Every app refers to specific functionality in the project. Examples of apps on websites are: forum, login page, shop, news, etc. We will create an app called the weather. Press Ctrl+C to stop the Django server and run the command:
python manage.py startapp weather
As you can see, Django has added a weather directory and some files in our project.
The next step is to register our app in Django. Open settings.py in the WeatherSite directory and add the weather app to the INSTALLED_APPS list:
INSTALLED_APPS = [ ‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.messages’, ‘django.contrib.staticfiles’, ‘weather’, ]
This tells Django that we want to use a weather app in our project.
We also need to provide Django with the URL that will be used by the weather app. Open file urls.py in the WeatherSite folder and modify it in the following way:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path(‘admin/’, admin.site.urls), path(”, include(‘weather.urls’)), ]
This tells Django that if we open URL 127.0.0.1:8000 with no other additions, it will redirect us to the weather app. If you want to use a few apps in your project, the path may be, for example, “weather/”. This means that the URL for the weather app will be 127.0.0.1:8000/weather/. Since we have only one app in our project, we won’t use an endpoint for the entry point to our app.
Now let’s create a urls.py file in the weather directory.
from django.urls import path from . import views urlpatterns = [ path(”, views.index), ]
This instruction tells Django that if we open URL 127.0.0.1:8000 it will run a function called “index” in the views.py file.
We haven’t created it yet, so let’s fix it.
from django.shortcuts import render def index(request): return render(request, ‘weather/index.html’)
For now, this function only renders the index.htm file. This is a template for our weather app. Go to the weather directory and create a directory named “templates”. Then go to the templates directory and create a directory named “weather”. Inside of the weather directory create a file called index.html. Here is the HTML we’ll use for our template:
<!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <title>WeatherApp</title> <link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css”> </head> <body> <div align=“center”> <h1>Weather in your city</h1> <form action=“” method=“get”> <input type=“text” id=“city” name=“city” placeholder=“Enter city”> <input type=“submit” name=“send” value=“Search”> </form> </div> </body> </html>
After all these actions, we can test our app. Go to your project root (WeatherSite directory), start the server, and go to 127.0.0.1:8000.
Now you can see the result of your HTML in the index.html file. You’ll see an input to see the weather in a specific city. But it doesn’t show any weather for now. In the next steps, we will use the ClimaCell API to show the weather in the city specified in the form.
Since ClimaCell API uses latitude and longitude in requests to return the weather data, we need to get coordinates of the city specified in the form. To do this we need some data of city coordinates. For this app, we will use the World Cities Database provided by simplemaps.com. Please download a free basic database. Unpack the wordcities.csv file in the main folder of the project (WeatherSite). In order to read wordcities.csv and search coordinates of cities we will use a python library called pandas.
Modify views.py in the weather directory:
from django.shortcuts import render import pandas as pd def index(request): df = pd.read_csv(‘worldcities.csv’) city = ‘Tokyo’ lat = df[df[‘city_ascii’] == city][‘lat’] lon = df[df[‘city_ascii’] == city][‘lng’]print(lat) print(‘n’) print(lon) return render(request, ‘weather/index.html’)
Let’s run the server and go to 127.0.0.1:8000. As you can see our site didn’t change in the browser. But we have the coordinates of Tokyo printed in the output.
0 35.685 Name: lat, dtype: float64 0 139.7514 Name: lng, dtype: float64
Stop the server with Ctrl+C.
Since we can get the latitude and longitude of the city, we can start working with ClimaCell API. Go to the ClimaCell API Endpoints on the RapidAPI and choose “Realtime” on the left side and Python(Requests) in the Code Snippets. Copy this code to the index function in views.py and modify it a little.
from django.shortcuts import render import pandas as pd import requests def index(request): df = pd.read_csv(‘worldcities.csv’) city = ‘Tokyo’ lat = df[df[‘city_ascii’] == city][‘lat’] lon = df[df[‘city_ascii’] == city][‘lng’]url = “https://climacell-microweather-v1.p.rapidapi.com/weather/realtime”querystring = {“unit_system”: “si”, “fields”: [“precipitation”, “precipitation_type”, “temp”, “cloud_cover”, “wind_speed”, “weather_code”], “lat”: lat, “lon”: lon}headers = { ‘x-rapidapi-host’: “climacell-microweather-v1.p.rapidapi.com”, ‘x-rapidapi-key’: “a1ca7cac7bmsh7481cbdd1b05541p170fb7jsnfb74af885ed7” }response = requests.request(“GET”, url, headers=headers, params=querystring).json() print(response) return render(request, ‘weather/index.html’)
Run the server and view the output:
{‘lat’: 35.685, ‘lon’: 139.7514, ‘temp’: {‘value’: 28.94, ‘units’: ‘C’}, ‘wind_speed’: {‘value’: 1.69, ‘units’: ‘m/s’}, ‘precipitation’: {‘value’: 0, ‘units’: ‘mm/hr’}, ‘precipitation_type’: {‘value’: ‘none’}, ‘cloud_cover’: {‘value’: 16.69, ‘units’: ‘%’}, ‘weather_code’: {‘value’: ‘mostly_clear’}, ‘observation_time’: {‘value’: ‘2020-08-09T20:49:31.079Z’}}
Now we have weather data for Tokyo obtained from the ClimaCell API. Then you can stop the server.
Since we have the data, we can display it on the website. Instead of printing the data to the output, let’s save it in the dictionary called context. To make data from context available for our template, we also need to add it as a third argument in the render function.
… def index(request): … context = {‘city_name’: city, ‘temp’: response[‘temp’][‘value’], ‘weather_code’: response[‘weather_code’][‘value’], ‘wind_speed’: response[‘wind_speed’][‘value’], ‘precipitation_type’: response[‘precipitation_type’][‘value’] } return render(request, ‘weather/index.html’, context) …
We need to modify the HTML inside the index.html to use variables from the context dictionary. Variables will use {{ }} tags.
<!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <title>WeatherApp</title> <link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css”> </head> <body> <div align=“center”> <h1>Weather in your city</h1> <form action=“” method=“get”> <input type=“text” id=“city” name=“city” placeholder=“Enter a city”> <input type=“submit” name=“send” value=“Search”> </form> <p> <h3>The weather in {{city_name}} is:</h3> <div>Weather conditions: {{weather_code}}</div> <div>Temperature: {{temp}} <sup>o</sup>C</div> <div>Wind speed: {{wind_speed}} m/s</div> <div>The type of precipitation: {{precipitation_type}}</div> </p> </div> </body> </html>
Let’s run the server and see what we have.
Now our app gets data from the ClimaCell API and displays current weather in Tokyo on the web page. The next and last step is to make our form work. Stop the server.
The data from our form will be sent to the backend by GET request because we don’t need to modify any database, we will just receive the city name and display the weather. Let’s change our index function in views.py. The final version of views.py will be:
from django.shortcuts import render import requests import pandas as pd def index(request): df = pd.read_csv(‘worldcities.csv’) if ‘city’ in request.GET: city = request.GET[‘city’] if df[df[‘city_ascii’] == city][‘city_ascii’].any(): lat = df[df[‘city_ascii’] == city][‘lat’] lon = df[df[‘city_ascii’] == city][‘lng’]url = “https://climacell-microweather-v1.p.rapidapi.com/weather/realtime”querystring = {“unit_system”: “si”, “fields”: [“precipitation”, “precipitation_type”, “temp”, “cloud_cover”, “wind_speed”, “weather_code”], “lat”: lat, “lon”: lon}headers = { ‘x-rapidapi-host’: “climacell-microweather-v1.p.rapidapi.com”, ‘x-rapidapi-key’: “a1ca7cac7bmsh7481cbdd1b05541p170fb7jsnfb74af885ed7” }response = requests.request(“GET”, url, headers=headers, params=querystring).json() context = {‘city_name’: city, ‘temp’: response[‘temp’][‘value’], ‘weather_code’: response[‘weather_code’][‘value’], ‘wind_speed’: response[‘wind_speed’][‘value’], ‘precipitation_type’: response[‘precipitation_type’][‘value’] } else: context = None else: context = None return render(request, ‘weather/index.html’, context)
Now the index function will check whether the request method is GET. If it is true, the function will search for the city variable obtained from the form. If the request contains the city variable, the index function will search the city’s coordinates. Then the index function will send the request to the ClimaCell API, obtain the weather data, write it to the context dictionary and render the template.
The last thing we need is to modify index.html:
<!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <title>WeatherApp</title> <link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css”> </head> <body> <div align=“center”> <h1>Weather in your city</h1> <form action=“” method=“get”> <input type=“text” id=“city” name=“city” placeholder=“Enter a city”> <input type=“submit” name=“send” value=“Search”> </form> {% if city_name %} <p> <h3>The weather in {{city_name}} is:</h3> <div>Weather conditions: {{weather_code}}</div> <div>Temperature: {{temp}} <sup>o</sup>C</div> <div>Wind speed: {{wind_speed}} m/s</div> <div>The type of precipitation: {{precipitation_type}}</div> </p> {% endif %} </div> </body> </html>
We added an ‘if’ statement to the HTML. Now it checks if the context contains a city_name variable. If it does, the template will display weather in the city that was specified in the form.
Our weather app is finished. Let’s check how it works! First of all, start the server and go to 127.0.0.1:8000.
As you can see, when you enter the site for the first time or don’t specify a city and hit the Search button, it doesn’t display any weather.
Let’s find out what the weather looks like in New York, for example.
After pressing the Search button, we get the result:
Now we have a simple weather app written in Python using the Django framework. It shows the real-time weather conditions in a specific city. We’ve used Django’s aspects like views, URLs, and templates. We’ve also learned how to work with the API to get weather data for our app.
The next possible step to improve your skills might be adding a weather forecast to the app. The free basic plan of ClimaCell API provides daily and hourly weather forecasts. Another option is to show the weather in several cities.
The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…
This January's release brings exciting features and improvements designed to empower you and your developers.…
Rapid API is committed to providing its users with the best possible experience, and the…
In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…
We're excited to announce the September 2023 Release Notes for the RapidAPI Enterprise Hub! Our…
We hope you enjoyed your summer! We're excited to announce the Rapid API Enterprise Hub…
View Comments
This api is not working
It worked! Thank you for the detailed tutorial
it would have been good, if you maintain this code to latest version or have atleast requirements.txt file
and also it would been good, if you have a git link to download code. as there very minute errors in your code, which waste time....