Skip to Main Content






Getting Started With APIs

Extracting and Manipulating Data

The following is some code that will demonstrate how to manipulate and extract data when using the Sunset Sunrise API.

The following code fetches the sunrise and sunset data for Montreal, Canada and displays the results using Matplotlib, through the following steps:

  1. Fetch the data from the API.
  2. Parse the response to extract the sunrise and sunset times.
  3. Use Matplotlib to plot these times.

Read through the code and identify what parts of it are new to the example, and what parts are the same. Being able to use Matplotlib is not an objective nor requirement of this workshop, so the following example only serves to show you one way that data can be manipulated after it is parsed.

Example Code:

# Import all the required libraries
import requests
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from dateutil import parser

# Define the coordinates for Montreal, Canada
latitude = 45.5017
longitude = -73.5673

# Define the base URL
url = "https://api.sunrise-sunset.org/json"

# Define the necessary parameters
params = {
    "lat": latitude,
    "lng": longitude,
    "formatted": 0  # Get the times in ISO 8601 format (UTC)
}

# Make a GET request to the API
response = requests.get(url, params=params)

# Parse the JSON response
data = response.json()

# Extract the sunrise and sunset times
sunrise_utc = data['results']['sunrise']
sunset_utc = data['results']['sunset']

# Convert UTC times to local time (Montreal is in the Eastern Time Zone, UTC-4)
sunrise = parser.isoparse(sunrise_utc) - timedelta(hours=4)
sunset = parser.isoparse(sunset_utc) - timedelta(hours=4)

# Prepare data for plotting
times = [sunrise, sunset]
labels = ['Sunrise', 'Sunset']
colors = ['orange', 'red']

# Use matplotlib to plot data
fig, ax = plt.subplots(figsize=(8, 6))
ax.bar(labels, [time.hour + time.minute / 60 for time in times], color=colors)

# Customize the plot
ax.set_ylabel('Time of Day (hours)')
ax.set_title('Sunrise and Sunset Times in Montreal, Canada')
ax.set_ylim([0, 24])
ax.set_yticks(range(0, 25, 1))
ax.grid(True)

# Annotate times
for i, time in enumerate(times):
    ax.text(i, time.hour + time.minute / 60 + 0.5, time.strftime('%H:%M'), ha='center', va='bottom')

# Show plot
plt.show()

Sample Output: