Python Programming: Building a Weather App with Flask

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating a Flask App
  5. Working with APIs
  6. Displaying Weather Data
  7. Conclusion

Introduction

In this tutorial, we will learn how to build a weather app using Python and the Flask web framework. By the end of the tutorial, you will be able to create a simple web application that retrieves weather data from an API and displays it on a webpage.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming language concepts. Familiarity with web development fundamentals will also be helpful, but not required.

Setup

Before we begin, make sure you have the following software installed:

  • Python 3 or higher
  • Flask (pip install flask)
  • requests (pip install requests)

You will also need an API key to access weather data. We will be using the OpenWeatherMap API in this tutorial. You can sign up for a free API key on their website.

Creating a Flask App

Let’s start by creating a new directory for our project and navigating into it. Open your terminal or command prompt and run the following commands: bash mkdir weather-app cd weather-app Next, create a new Python file called app.py using your favorite text editor. This file will contain the main code for our Flask app. ```python from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Weather App!"

if __name__ == '__main__':
    app.run()
``` In the above code, we import the Flask module and create an instance of the Flask class. We define a route `/` and a function `home()` that returns the string "Welcome to the Weather App!". Finally, we run the Flask app if the script is executed directly.

Save the file and return to your terminal or command prompt. Run the following command to start the Flask development server: bash python app.py You should see an output similar to: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Open your web browser and navigate to http://localhost:5000. You should see the message “Welcome to the Weather App!” displayed on the webpage.

Working with APIs

Now that we have our basic Flask app set up, let’s work on integrating the OpenWeatherMap API to retrieve weather data. We will use the requests library to send HTTP requests and handle API responses.

First, import the requests module in app.py. python import requests Next, we need to define a function that will fetch weather data from the API. Add the following code to app.py: ```python def get_weather(city): api_key = ‘YOUR_API_KEY’ url = f’http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}’ response = requests.get(url) data = response.json()

    return data
``` Replace `'YOUR_API_KEY'` with your actual OpenWeatherMap API key.

The get_weather() function takes a city parameter and constructs a URL with the city name and API key. It sends a GET request to the API endpoint and parses the JSON response using the json() method. The function then returns the weather data as a Python dictionary.

Displaying Weather Data

Let’s modify the home() function to display the weather information on the webpage. Update the code as follows: python @app.route('/') def home(): data = get_weather('London') return f"Weather in {data['name']}: {data['weather'][0]['description']}" In this example, we are fetching the weather data for London by passing 'London' as the argument to get_weather(). We then access specific information from the response JSON, such as the city name and weather description, and display it on the webpage.

Save the file and restart the Flask server: bash python app.py Visit http://localhost:5000 in your web browser, and you should now see the weather information for London displayed on the webpage.

You can modify the home() function to display the weather data for any city by passing the city name as an argument to get_weather().

Conclusion

In this tutorial, we have learned how to build a weather app using Python and Flask. We used the OpenWeatherMap API to fetch weather data and displayed it on a webpage. You are now able to create your own weather application and customize it further by adding more features and styling.

Remember to properly handle errors and validate user input when working with APIs.