AI & Data

Working with REST APIs

Lecture 3

Fetching and integrating data from web APIs for machine learning and data analysis projects

Introduction to Web APIs

How REST APIs Work

Making Your First API Request

We use the requests library in Python.


import requests

# Define the API endpoint URL
url = "https://jsonplaceholder.typicode.com/posts/1"

# Send a GET request
response = requests.get(url)

# The response object contains server's response
print(response.status_code)  # e.g., 200
print(response.json())       # The data in JSON format
    

Understanding the Response

Exercise 1: Simple GET Request

Working with API Parameters

Passing query parameters with requests:


params = {'userId': 1}
response = requests.get('.../posts', params=params)
print(response.url) # See the final URL
    

Exercise 2: Filtering API Results

Handling Authentication


headers = {'Authorization': 'Bearer YOUR_API_KEY'}
response = requests.get(url, headers=headers)
    

Exercise 3: Error Handling

Integrating with Orange Data Mining


from Orange.data import Table, Domain, ContinuousVariable, StringVariable
import requests

# 1. Fetch data from API
users_data = requests.get('.../users').json()

# 2. Define the domain (the columns)
domain = Domain([
    StringVariable('name'),
    StringVariable('email'),
    StringVariable('city')
])

# 3. Create the data table
data = [[u['name'], u['email'], u['address']['city']] for u in users_data]
out_data = Table.from_list(domain, data)
    

Final Exercise: World Countries Data

Slide Overview