Python code to fetch weather data

You can download weather data from the Internet. First you need to install the requests library

!pip install requests

Code to fetch weather data

import requests

# Define the API endpoint and API key
api_endpoint = "http://api.openweathermap.org/data/2.5/weather"
api_key = "YOUR_API_KEY"

# Define the city and country for which to fetch the weather data
city = "London"
country = "UK"

# Build the API URL
url = f"{api_endpoint}?q={city},{country}&appid={api_key}"

# Fetch the weather data from the API
response = requests.get(url)

# Check if the API request was successful
if response.status_code == 200:
    # Print the weather data
    weather_data = response.json()
    print(weather_data)
else:
    # Print an error message if the API request was not successful
    print("Failed to fetch weather data")

This code uses the requests library to fetch weather data from the OpenWeatherMap API. The API endpoint and API key are defined, and the API URL is built using the f"{api_endpoint}?q={city},{country}&appid={api_key}" syntax. The get function is used to fetch the weather data from the API, and the status_code attribute is used to check if the API request was successful. If the API request was successful, the weather data is printed in JSON format. If the API request was not successful, an error message is printed.

Unit Test

import unittest
import requests

class TestWeatherData(unittest.TestCase):
    def test_fetch_weather_data(self):
        # Define the API endpoint and API key
        api_endpoint = "http://api.openweathermap.org/data/2.5/weather"
        api_key = "YOUR_API_KEY"

        # Define the city and country for which to fetch the weather data
        city = "London"
        country = "UK"

        # Build the API URL
        url = f"{api_endpoint}?q={city},{country}&appid={api_key}"

        # Fetch the weather data from the API
        response = requests.get(url)

        # Check if the API request was successful
        self.assertEqual(response.status_code, 200)
        
        # Check if the weather data is returned in the response
        self.assertTrue("weather" in response.json())

if __name__ == '__main__':
    unittest.main()

This code uses the unittest module to write unit tests for the code to fetch weather data. The TestWeatherData class is defined to contain the tests, and the test_fetch_weather_data method is defined to contain the test. The test checks if the API request was successful by checking if the status_code attribute of the response is equal to 200. The test also checks if the weather data is returned in the response by checking if the “weather” key is present in the JSON data returned in the response.