DEV Community

Kyle Y. Parsotan
Kyle Y. Parsotan

Posted on

Build and Deploy a Weather Flask Application Using OpenWeatherMap (Step-by-Step Guide)

Introduction

Want to learn Flask by building a real-world project? In this tutorial, you'll create a weather web application using Python Flask and the OpenWeatherMap API. The application allows user to search for any city and instantly view its current weather conditions.

By the end of this guide, you'll know how to:
Install Flask
Create a Flask project
Get a OpenWeatherMap API key
Connect the API to your application
Design a simple weather dashboard
Run the application on your local machine or use docker or a database.

Project Overview
The application includes:
City Search
Current temperature
Humidity
Wind Speed
Weather Icon
Responsive User Interface

Prerequisites

Project Overview

The application includes:
Prerequisites
Before starting, install:

Python 3.14 or later
pip
Visual Studio Code (recommended)

Step 1: Create the Project Folder

Open Terminal or Command Prompt.
mkdir weather-flask-app
cd weather-flask-app

Image 1: Terminal showing the project folder creation.

Step 2: Create a Virtual Environment

Windows
python -m venv venv
venv\Scripts\activate

Linux/MacOS
source venv/bin/activate

You should now see:
(venv)

Before your terminal prompt.

Image 2: Activate virtual environment in the terminal

Step 3: Install Required Packages

Install Flask and Requests.

pip install flask requests

Verify Installations:

pip list

📷 Image 3: Installed Flask packages.

Step 4: Create the Project Structure

Create the following folders and files.

weather-flask-app/
│
├── app.py
├── templates/
│ └── index.html
├── static/
│ └── style.css
└── venv/

📷 Image 4: Project structure in VS Code Explorer.

Step 5: Create an OpenWeatherMap API Key

Visit the OpenWeatherMap website.
Create a free account.
Log in.
Navigate to API Keys.
Copy your generated API key.

Example:

API_KEY = your_api_key_here

📷 Image 5: OpenWeatherMap dashboard displaying the API key page.

Step 6: Create the Flask Backend

Create app.py.

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

API_KEY = "YOUR_API_KEY"

@app.route("/", methods=["GET", "POST"])
def index():
    weather = None

    if request.method == "POST":
        city = request.form["city"]

        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"

        response = requests.get(url).json()

        if response.get("cod") == 200:
            weather = {
                "city": response["name"],
                "temperature": response["main"]["temp"],
                "description": response["weather"][0]["description"],
                "humidity": response["main"]["humidity"],
                "wind": response["wind"]["speed"],
                "icon": response["weather"][0]["icon"]
            }

    return render_template("index.html", weather=weather)

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode


python

📷 Image 6: app.py open in VS Code.

Step 7: Create the HTML Template

Create templates/index.html.

<!DOCTYPE html>
<html>
<head>
    <title>Weather App</title>
    <link rel="stylesheet" href="/static/style.css">
</head>

<body>

<div class="container">

<h1>Weather Application</h1>

<form method="POST">
<input type="text" name="city" placeholder="Enter city name">
<button type="submit">Search</button>
</form>

{% if weather %}

<h2>{{ weather.city }}</h2>

<img src="https://openweathermap.org/img/wn/{{ weather.icon }}@2x.png">

<p>Temperature: {{ weather.temperature }} °C</p>

<p>Weather: {{ weather.description }}</p>

<p>Humidity: {{ weather.humidity }}%</p>

<p>Wind Speed: {{ weather.wind }} m/s</p>

{% endif %}

</div>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode


html

📷 Image 7: HTML page inside VS Code.

Step 8: Add CSS Styling

Create static/style.css.

body{
font-family:Arial;
background:#4facfe;
background:linear-gradient(to right,#00f2fe,#4facfe);
display:flex;
justify-content:center;
align-items:center;
height:100vh;
}

.container{
background:white;
padding:30px;
border-radius:15px;
text-align:center;
box-shadow:0 5px 15px rgba(0,0,0,.2);
}

input{
padding:10px;
width:220px;
}

button{
padding:10px 20px;
background:#2196F3;
color:white;
border:none;
cursor:pointer;
}
Enter fullscreen mode Exit fullscreen mode

📷 Image 8: Styled weather application.

Step 9: Run the Flask Application

Run:

python app.py

Output:

Open your browser and visit:

http://127.0.0.1:5000

📷 Image 9: Terminal showing the Flask development server.

Step 10: Test the Application

Search for cities such as:

London
New York
Tokyo
Paris
Delhi

The application displays:

City name
Current temperature
Weather condition
Humidity
Wind speed
Weather icon

📷 Image 10: Weather results displayed after searching for a city.

How the Application Works
User enters a city name.
Flask receives the request.
Requests sends an HTTP request to the OpenWeatherMap API.
The API returns weather data in JSON format.
Flask extracts the required fields.
The template displays the weather information.
Common Errors
Invalid API Key

Error:

401 Unauthorized

Solution:

Use the correct API key and wait a few minutes after generating it if it is newly created.

City Not Found

Error:

404

Solution:

Check the spelling of the city name.

Module Not Found

Error:

ModuleNotFoundError

Solution:

Install the missing package:

pip install flask requests
Future Improvements

You can extend the application by adding:

5-day weather forecast
Air quality information
Geolocation support
Dark mode
Weather maps
Search history
Favorite cities
Temperature unit conversion (°C/°F)
Conclusion

Congratulations! You have built a complete Weather Flask application using Python and the OpenWeatherMap API. Along the way, you learned how to create a Flask project, integrate a third-party REST API, build a responsive web interface, and run the application locally. This project is an excellent starting point for learning web development with Flask and can be enhanced with additional features such as weather forecasts, user authentication, and cloud deployment.

Top comments (0)