Python is a growing language that has become increasingly popular in the programming community. One of Python’s key features is that it’s easy to work with APIs on websites and many weather entities have their API which you can access with just a couple of lines of code. One such great API is the Open Weather Map’s API, with it you can build a small program to access any given location’s weather forecast anywhere across the globe! This article will help you to get weather information using Python.

What is OpenWeatherMap

The OpenWeatherMap (OWM) is a helpful and free way to gather and display weather information. Because it’s an open-source project, it’s also free to use and modify in any way. OWM offers a variety of features and is very flexible. Because of these qualities, it offers a lot of benefits to developers. One of the major benefits of OWM is that it’s ready to go. Unlike other weather applications, OWM has a web API that’s ready to use. You don’t have to install any software or set up a database to get it up and running. This is a great option for developers who want to get weather reading on a website quickly and efficiently. 

It has an API that supports HTML, XML, and JSON endpoints. There is a limited free usage tier, but make more than 60 calls per min, a subscription must be purchased starting at USD 40 per month. To access historical data, a subscription is required starting at 150 USD per month. Current weather information extended forecasts, and graphical maps can be requested by users. These maps show cloud cover, wind speed as well as pressure, and precipitation.

Prerequisites & Configuration

Get an API Key

The first thing you need to do is create an API key with the OpenWeatherMap. The API key will let your app know that it’s authorized to connect to the API. Once you have your API key, you’ll be able to access the API documentation.

To get an API key you’ll need to create a free user account on OpenWeatherMap. Here’s how you can do it:

  1. In order to get weather information using python, we need to visit this link.
  2. Click on the Subscribe button of the Current Weather Data section.
  3. Click on the Get API key on the free section.
  4. Now create an account here, then follow through with the email confirmation procedures.
  5. After going through the above steps go to the Members page and click the API keys item at the top of the page.
  6. Here you either create a new API key or use the preexisting one.

Install Requests

The Requests library is used for sending HTTP requests and interacting with web servers. It simplifies tasks like POSTing and GETing with URL endpoints, and forms, and has support for powerful extensions, like using a proxy, web sockets, and much more. You can run the following command or download its files to install requests.

pip3 install requests

Creating a Simple Weather Showing Python App 

Now that we have an API to get the current weather, we’re going to create a simple app that can show the current weather of any location! Here is how we’re going to do it:

import requests

api_key = "AAAAPPPPIIII_____KKKKEEEEYYYY"  # Enter the API key you got from the OpenWeatherMap website
base_url = ""

city_name = input("Enter city name : ")
complete_url = base_url + "appid=" + 'd850f7f52bf19300a9eb4b0aa6b80f0d' + "&q=" + city_name  # This is to complete the base_url, you can also do this manually to checkout other weather data available
response = requests.get(complete_url)
x = response.json()

if x["cod"] != "404":
    y = x["main"]

    current_temperature = y["temp"]
    z = x["weather"]

    weather_description = z[0]["description"]

    print(" Temperature (in kelvin unit) = " +
                    str(current_temperature) +
          "\n description = " +

    print(" City Not Found ")

Run this file running it directly in your IDE or a terminal by specifying the file’s whole location and name. You can find out a file’s whole location with PWD. 

If it worked successfully, you should see a result something like this:

linux@linux-System-Product-Name:~/Desktop/Weather_predition$ /bin/python3 /home/linux/Desktop/Weather_predition/
Enter city name : paris
Temperature (in kelvin unit) = 285.77
atmospheric pressure (in hPa unit) = 1019
humidity (in percentage) = 91
description = broken clouds

If you understood the code above, you can almost do anything you want with it. There are some tricky parts to it, but if you stick to it, you can even make a fully-fleshed desktop or web application with it. Just to show you, in the next section, we’re going to be making a bare-bones web page with Flask utilizing requests to show the weather of any location on an HTML page.

Creating a Simple Flask Page for Showing Weather 

Since we have already done the configurations mentioned above, we can start directly by creating a basic flask application.

Note: If you don’t have Flask installed already, you can install it with:

pip install django                                                                                                                                                                                                                             
from flask import Flask, render_template, request
import requests

app = Flask(__name__)

if __name__ == '__main':

This is a simple Flask application with now functions in it, we need to customize it that we can show our weather details from there on a template. To do that, add the following line in this file like so:

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/temperature', methods=['POST'])
def temperature():
    city_name = request.form['zip']
    r = requests.get(''+ "appid=" + "d850f7f52bf19300a9eb4b0aa6b80f0d" + "&q=" + city_name) # Enter your API key
    json_object = r.json()
    temp_k = float(json_object['main']['temp'])
    temp_f = (temp_k - 273.15)
    return render_template('temperature.html', temp=temp_f)

def index():
return render_template('index.html')

if __name__ == '__main__':

Also, add the template file to your project folder.

# index.html

<title>Request Example</title>
<form method="POST" action="/temperature">
City name/zip : <input type="text" name="zip">
<input type="submit">

# temperature.html

<head><title>Current Temperature</title></head>
<h1> The current temperature (C) is : {{ temp }} degrees. </h1>

Now, after putting all the files in the same folder you can run with the same method as told  above; and you should get a result like this:

linux@linux-System-Product-Name:~/Desktop/python-weather-api-master$ /bin/python3 /home/linux/Desktop/python-weather-api-master/
* Serving Flask app 'test' (lazy loading)
* Environment: production
  WARNING: This is a development server. Do not use it in a production deployment.
  Use a production WSGI server instead.
* Debug mode: on
* Running on (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 121-505-311

From here you can open the link given above and you should be directed to this page:

get-weather-information-using python-1

Here, you can put the name or zip code of the city you want to know the temperature of and you get the result as:


And it’s done!! You can customize it from here and may add a bit more functionality to it. The OpenWeatherMap has great documentation and the request library can be used in many other that than this which can provide you with even more functionality and features to put in the application. You can simply connect to the OWM API and get weather information using Python.

Here are some useful tutorials that you can read: