Welcome to Foundation of Data Science Laboratory
Welcome to Foundation of Data Science Laboratory
2.2.2.API Integration:
Identify a public API (e.g., OpenWeatherMap, CoinGecko).
Use Python to fetch data from the API and store it in a DataFrame.
Display the first few rows of the DataFrame.
Here's a Python code example that demonstrates how to integrate with the CoinGecko public API to fetch cryptocurrency data, store it in a Pandas DataFrame, and display the first few rows of the DataFrame.
Make sure you have the necessary libraries installed:
pip install requests pandas
Here’s how you can fetch cryptocurrency data from the CoinGecko API:
import requests
import pandas as pd
# Step 1: Identify the URL of the public API
url = "https://api.coingecko.com/api/v3/coins/markets"
params = {
'vs_currency': 'usd', # Currency to convert the cryptocurrency to
'order': 'market_cap_desc', # Order by market cap descending
'per_page': 10, # Number of results per page
'page': 1 # Page number
}
# Step 2: Send a request to fetch the data from the API
response = requests.get(url, params=params)
# Step 3: Check if the request was successful
if response.status_code == 200:
data = response.json() # Parse JSON response
else:
print("Failed to retrieve data")
data = []
# Step 4: Convert the data into a DataFrame
df = pd.DataFrame(data)
# Step 5: Display the first few rows of the DataFrame
df.head()
id symbol name ... market_cap total_volume price_change_percentage_24h
0 bitcoin btc Bitcoin ... 4444478523614 22117572721 2.65
1 ethereum eth Ethereum ... 2283812617914 12454037944 2.75
2 tether usdt Tether ... 723920982189 48153913423 0.04
3 binancecoin bnb Binance Coin ... 391621354529 1225272076 3.12
4 usd-coin usdc USD Coin ... 272037434413 27469296424 0.03
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()).