ScriptCrew

Weather API Tutorial

Shrenik Sairam

Step-by-Step Instructions

Step 1: Set Up a Virtual Environment

Before writing the script, create and activate a virtual environment:

python3 -m venv venv
source venv/bin/activate  # Linux/macOS
venv\Scripts\activate  # Windows

Step 2: Install Required Library

Inside the virtual environment, install the requests library:

pip install requests

Step 3: Get an OpenWeatherMap API Key

Go to OpenWeatherMap, sign up, and get your API key.

Step 4: Write the Python Script


  # Import the requests library to handle HTTP requests
  import requests

  # Change this to your desired city
  city_name = 'New Delhi'  # Example: New Delhi

  # Replace with your actual API key
  API_key = 'your_api_key_here'  

  # Construct the API URL with the specified city and API key
  url = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_key}&units=metric'

  # Send a GET request to the API endpoint
  response = requests.get(url)

  # Check if the HTTP request was successful (status code 200 means success)
  if response.status_code == 200:
      data = response.json()  #Convert the JSON response into a Python dictionary
      
      # Extract and print weather information:
      # 'weather' is a list that contains a dictionary with weather details. [0] is used to access the first element.
      # 'description' provides a text summary of the weather (e.g., "clear sky", "rain").
      print('Weather:', data['weather'][0]['description'])
      
      # 'main' is a key in the response containing temperature-related data.
      # 'temp' holds the current temperature in Celsius.
      print('Temperature:', data['main']['temp'], '°C')
      
      # 'feels_like' gives the perceived temperature based on humidity and wind conditions.
      print('Feels Like:', data['main']['feels_like'], '°C')
      
      # 'humidity' holds the percentage of humidity in the air.
      print('Humidity:', data['main']['humidity'], '%')
  else:
      # If the request was not successful, print an error message
      print("Error fetching data")