Create a Weather App using API in Python

Create a Weather App using API in Python

Hello Coders, welcome to the CodeWithRandom blog!
Are you curious about how to build your own weather app in Python? In this tutorial, we are creating a Weather App using API in Python. If you study Python and want to create a project, then this is a very interesting project, perfect for you!

Create a Weather App using API in Python

We will use a weather API (like WeatherAPI, fetch live weather data, and display it in the terminal. No fancy GUI required – just logic, API calls, and Python magic.  Today, we are going to build a Weather App using Python and a free Weather API. This project is beginner-friendly and will help you learn how to interact with APIs in Python. No GUI, no complexities – just simple Python + API magic.

This project is perfect for beginners who want to practice working with APIs, JSON data, and Python libraries. You only need some basic knowledge of Python to get started.

Let’s start :

What Will You Learn in the Weather project?

  1. How to use a public API in Python

  2. How to make HTTP requests using requests library

  3. How to parse and display JSON data

  4. How to structure a basic CLI-based app

  5. Importance of API keys and documentation

Why This Weather Project?

This is one of the most searched and trending beginner projects in Python right now. Many new developers want to learn how to integrate APIs in real projects, and this is the perfect place to start.

This app can be further upgraded with a GUI, voice input, or even converted to a web app – so this is an excellent base project.

What is an API?

API (Application Programming Interface) is a way for one piece of software to interact with another. In this project, we’ll use the free and powerful WeatherAPI to fetch weather details for any city.

Tools and Technologies
  1. Python 3.6+

  2. requests module

  3. WeatherAPI (Sign up for a free key)

  4. Terminal / VS Code / Command Line

Install Required Module

pip install requests

Get Your API Key

Go to weatherapi.com, sign up for a free account, and copy your API key. We’ll need it to authenticate requests.

Python Weather App Code

  • Showing temperature in both Celsius and Fahrenheit
  • Displaying feels like temperature
  • Showing local time of the city
  • Adding error handling for invalid inputs / network issues
  • Asking user if they want to check multiple cities in one run

import requests
import time

def get_weather(city, api_key):
    """
    Fetches and displays the weather information for a given city
    using WeatherAPI.
    """
    url = f"http://api.weatherapi.com/v1/current.json?key={api_key}&q={city}&aqi=no"

    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            data = response.json()

            location = data['location']
            current = data['current']

            print("\n===============================")
            print(f"📍 City: {location['name']}, {location['country']}")
            print(f"🕒 Local Time: {location['localtime']}")
            print("-------------------------------")
            print(f"🌡️ Temperature: {current['temp_c']}°C | {current['temp_f']}°F")
            print(f"🤔 Feels Like: {current['feelslike_c']}°C | {current['feelslike_f']}°F")
            print(f"🌤️ Condition: {current['condition']['text']}")
            print(f"💧 Humidity: {current['humidity']}%")
            print(f"💨 Wind: {current['wind_kph']} kph ({current['wind_dir']})")
            print(f"☁️ Cloud Cover: {current['cloud']}%")
            print("===============================\n")

        else:
            print("❌ Error: City not found or invalid API response.")

    except requests.exceptions.Timeout:
        print("⏰ Request timed out. Please check your internet connection.")
    except requests.exceptions.RequestException as e:
        print("⚠️ An error occurred:", e)


if __name__ == "__main__":
    api_key = "Your_API"  # 🔑 Replace with your WeatherAPI key

    print("=== 🌎 Python Weather App ===")
    while True:
        city = input("\nEnter city name (or type 'exit' to quit): ").strip()
        if city.lower() == "exit":
            print("👋 Exiting Weather App. Stay safe!")
            break

        if city == "":
            print("⚠️ Please enter a valid city name.")
            continue

        get_weather(city, api_key)

        # Small pause for readability
        time.sleep(1)

Added local time of the city

Displays both Celsius & Fahrenheit

Shows “feels like” temperature

Includes cloud cover info

Handles timeouts & network errors

Allows checking multiple cities in one session

Clean menu-style output formatting

Code Output Preview:

Create a Weather App using API in Python

Video Preview

What’s Happening in the Code?

  • We are used requests.get() to calling the API.
  • The response is in JSON format – we parse it using .json().
  • The weather details are printed in a clean format.
  • If an error occurs (like the wrong city), it’s handled.

Building a Weather App using API in Python is a perfect project to understand how real-world apps use data from external sources. It’s beginner-friendly, scalable, and widely searched by learners and tech enthusiasts. We hope you enjoyed building this with us!

Stay connected with CodeWithRandom for more such cool Python projects.

Thanks For Reading the Blog!

 

FAQs

 

Q. Is this Weather API free?
Yes, for basic usage and personal projects, it’s completely free.

 

Q. Can I get the weather by coordinates?
Yes! Just replace the city name with the lat, long in the q parameter.

 

Q. Is it possible to get the weather forecast for the next 3 days?
Yes, just use the forecast.json endpoint instead of current.json.

I'm a Freelancer and Article Author

Leave a Comment