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 CoinGecko
url = "https://api.coingecko.com/api/v3/coins/markets"
params = {
"vs_currency": "usd", # Currency to compare against
"order": "market_cap_desc", # Sort by market cap descending
"per_page": 10, # Number of coins to fetch
"page": 1, # Page number for pagination
"sparkline": "false" # Exclude sparkline data for simplicity
}
# Make a GET request to the CoinGecko 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 pandas DataFrame
data = response.json()
df = pd.DataFrame(data)
# Display the first few rows of the DataFrame
print(df.head())
else:
print(f"Failed to fetch data. Status code: {response.status_code}")
Some bold text
Paragraph
API Endpoint: The program accesses the CoinGecko API endpoint that provides market data for cryptocurrencies.
Parameters: The params dictionary specifies:
vs_currency: Base currency (e.g., "usd").
order: Order by market cap (descending).
per_page: Number of items per page.
page: Page number.
sparkline: Set to "false" to exclude additional data.
Request and Response: It makes a GET request using requests.get() with the specified URL and parameters.
DataFrame Creation: The response is converted into a pandas DataFrame.
Display: The first few rows of the DataFrame are displayed using print(df.head()).