1 Oct 2023

Building a Command-Line Weather App with Python: Using APIs for Data Retrieval

Weather is an ever-changing phenomenon that affects our daily lives in numerous ways. Whether you're planning a weekend trip, deciding what to wear, or simply curious about the weather in your area, having a command-line weather app can be incredibly handy. In this tutorial, we will walk you through the process of building a simple yet powerful command-line weather application using Python and API (Application Programming Interface) for data retrieval.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Getting Started 
       3.1 Installing Required Libraries
       3.2 Signing up for a Weather API Key
  4. Understanding APIs and Weather Data
       4.1 What is an API?
       4.2 Choosing a Weather API
       4.3 API Endpoint and Parameters
  5. Building the Weather App
       5.1 Project Structure
       5.2 Writing the Code
  6. Running the App
  7. Conclusion

Introduction

In this blog post, we'll guide you through the step-by-step process of creating a command-line weather application using Python. The app will allow users to fetch current weather information for a given location using an external weather API.

Prerequisites

Before we get started, make sure you have the following prerequisites in place

Getting Started

Installing Required Libraries

We will be using the requests library to interact with the weather API. To install it, open your terminal (or command prompt) and run the following command:pip install requests

Signing up for a Weather API Key

To fetch weather data, we'll need an API key from a weather service provider. There are several free and paid options available. For this tutorial, we will use the OpenWeatherMap API, which offers a free tier that provides enough data for our needs.

Head over to the [OpenWeatherMap website](https://openweathermap.org/) and sign up for a free account. After registration, you'll be provided with an API key, which we'll use to make API requests.

Understanding APIs and Weather Data

What is an API?

An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. In our case, we'll be using the API provided by OpenWeatherMap to access weather data.

APIs work through HTTP requests, and they usually return data in JSON format, which is easily parseable by Python.

Choosing a Weather API

There are several weather APIs available, each with its own features and limitations. Some popular ones include OpenWeatherMap, WeatherStack, and AccuWeather. For this tutorial, we chose OpenWeatherMap due to its ease of use and the availability of a free tier.

API Endpoint and Parameters

An API endpoint is a specific URL to which we send our requests. For OpenWeatherMap, the endpoint for fetching weather data is:https://api.openweathermap.org/data/2.5/weather

To make a request, we'll need to provide the API key as a parameter, along with the location for which we want to fetch the weather data. OpenWeatherMap allows us to specify the location using either city name or geographic coordinates (latitude and longitude).

Now that we understand the basics of APIs and weather data, let's start building our command-line weather app.

Building the Weather App

Project Structure

Before we start coding, let's plan the project structure. We'll create a single Python script for our weather app, but you can always expand it into a more complex project with multiple modules if desired. The basic structure will be as follows

weather_app/
  ├── app.py
  └── api_key.txt

Writing the Code

Now, let's dive into the code. Open your favorite text editor or IDE and create a new file named app.py.

# app.py

import requests

def get_weather(api_key, location):
    url = f"https://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": location,
        "appid": api_key,
        "units": "metric"  # Change to "imperial" for Fahrenheit
    }

    response = requests.get(url, params=params)
    data = response.json()

    if response.status_code == 200:
        # Extract relevant weather information from the API response
        weather_data = {
            "location": data["name"],
            "description": data["weather"][0]["description"],
            "temperature": data["main"]["temp"],
            "humidity": data["main"]["humidity"],
            "wind_speed": data["wind"]["speed"]
        }
        return weather_data
    else:
        print(f"Error: {data['message']}")
        return None

def main():
    with open("api_key.txt") as f:
        api_key = f.read().strip()

    location = input("Enter the city name or coordinates (latitude,longitude): ")
    weather_data = get_weather(api_key, location)

    if weather_data:
        print(f"Weather in {weather_data['location']}:")
        print(f"Description: {weather_data['description']}")
        print(f"Temperature: {weather_data['temperature']}°C")
        print(f"Humidity: {weather_data['humidity']}%")
        print(f"Wind Speed: {weather_data['wind_speed']} m/s")

if __name__ == "__main__":
    main()

The app.py script contains two main functions. The get_weather function makes an API request to OpenWeatherMap, passing the API key and location as parameters, and returns the weather data in a dictionary format.

The main function reads the API key from the api_key.txt file, prompts the user for a location, calls the get_weather function to fetch weather data, and then displays the results on the command line.

Running the App

To run the app, save the app.py file and create a new file named api_key.txt in the same directory, and paste your OpenWeatherMap API key into this file.

Now, open your terminal (or command prompt), navigate to the project directory, and run the following command:python app.py

The app will prompt you to enter a city name or geographic coordinates (latitude, longitude). After providing the location, the app will fetch and display the current weather data for that location.

Conclusion

Congratulations! You have successfully built a command-line weather application using Python and an external weather API. This project is a great starting point for learning about APIs, making HTTP requests, and processing JSON data.

Feel free to enhance the app by adding features such as weather forecasts, displaying weather icons, or providing additional information like sunrise and sunset times. Additionally, you can explore other weather APIs or even consider building a graphical user interface (GUI) version of the app.

Remember to keep your API key safe and avoid

 sharing it publicly, as it grants access to your API usage limits and potentially sensitive data.

You may also like

Building a Command-Line Weather App with Python

In this blog, we explored the process of building a command-line wea...

Continue reading

Python API Integration with Requests and Tweepy

Python is a powerful programming language that can be used to integr...

Continue reading

Building a Weather Forecast App with Python

In this tutorial, we will guide you through the process of building ...

Continue reading