Welcome to Foundation of Data Science Laboratory
Welcome to Foundation of Data Science Laboratory
2.2.2 API Integration:
o Identify a public API (e.g., OpenWeatherMap, CoinGecko).
o Use Python to fetch data from the API and store it in a
DataFrame.
o Display the first few rows of the DataFrame.
Step 1: Install Required Libraries
pip install requests pandas
import requests
import pandas as pd
# Define the API endpoint for OpenWeatherMap
url = "http://api.openweathermap.org/data/2.5/weather"
# Replace 'your_api_key' with your actual OpenWeatherMap API key
api_key = 'your_api_key'
# Specify the city for which you want to fetch weather data
city = "London"
# Define parameters for the API request
params = {
"q": city,
"appid": api_key,
"units": "metric" # Use "metric" for Celsius
}
# Make a GET request to the OpenWeatherMap API
response = requests.get(url, params=params)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Convert the JSON response to a dictionary
data = response.json()
# Extract relevant information from the data
weather_data = {
"City": [data["name"]],
"Weather": [data["weather"][0]["description"]],
"Temperature (C)": [data["main"]["temp"]],
"Humidity (%)": [data["main"]["humidity"]],
"Wind Speed (m/s)": [data["wind"]["speed"]]
}
# Create a pandas DataFrame from the dictionary
df = pd.DataFrame(weather_data)
# Display the first few rows of the DataFrame
print(df.head())
else:
print(f"Failed to fetch data. Status code: {response.status_code}")
City Weather Temperature (C) Humidity (%) Wind Speed (m/s)
0 London light rain 15.0 82 5.1
API Endpoint: Uses the OpenWeatherMap API endpoint for fetching weather data.
API Key: Replace 'your_api_key' with your actual API key.
City Parameter: Specifies the city for which you want to retrieve weather data (e.g., London).
Units Parameter: Uses "metric" to get temperature data in Celsius.
Request and Response: Makes a GET request with requests.get().
Data Extraction: Extracts data like city name, weather description, temperature, humidity, and wind speed.
DataFrame Creation: Stores this data in a pandas DataFrame and displays the first few rows using print(df.head()).