Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/03-working-with-apis/03-working-with-apis.ipynb

View source on GitHub

Module 03: Working with APIs#

Fetch data from the web with AI assistance.

Learning Objectives#

  1. Understand REST API concepts

  2. Use Python requests library

  3. Work with the OpenAlex scholarly API

  4. Have AI write API boilerplate

  5. Parse and process JSON responses

What is an API?#

API (Application Programming Interface): A way for programs to communicate.

REST API: Uses HTTP requests to access and manipulate data.

HTTP Methods#

Method

Purpose

Example

GET

Retrieve data

Get a user’s profile

POST

Create data

Create a new post

PUT

Update data

Update user info

DELETE

Remove data

Delete a comment

Context Engineering Reminder (from Module 00)

Before starting this exercise, think about what context the agent needs. For API work, that means:

  • Fetch the API documentation before asking the agent to write API calls — training data may have outdated endpoints

  • Show the agent a sample API response (save one to a JSON file) so it knows the data structure

  • If you hit an error, paste the full response (status code + body), not just “it didn’t work”

Load the context first, then ask for the action.

Exercise 1: Explore an API in the Browser (5 min)#

Before writing any code, let’s see what an API response actually looks like.

  1. Open this URL in your browser (just click or paste it):

    https://api.openalex.org/works?search=machine+learning&per_page=3

  2. You should see a JSON response. Look at it and answer these questions:

    (a) How many total results matched the search? (Look for meta.count near the top of the response.)

    (b) What fields does each work have? (Scroll through one of the items in results — you’ll see title, publication_year, cited_by_count, etc.)

    (c) What is the title of the first result?

  3. Try modifying the URL — change machine+learning to your own research interest and reload.

Key insight: This is exactly what your Python code will do — send a request to this URL and parse the JSON response. The browser is just a simple HTTP client.

import requests
import json

# Simple GET request
response = requests.get('https://api.github.com')

print(f"Status Code: {response.status_code}")
print(f"Content Type: {response.headers['content-type']}")

Exercise 2: Your First API Call (10 min)#

Now let’s do the same thing programmatically. In a new code cell below, write Python code to:

  1. Search for Carnegie Mellon University using the OpenAlex institutions endpoint:

    import requests
    response = requests.get("https://api.openalex.org/institutions", params={"search": "carnegie mellon"})
    
  2. Print the status code — is it 200 (success)?

  3. Parse the JSON response:

    data = response.json()
    
  4. Print the display_name and works_count of the first result:

    first = data['results'][0]
    print(f"Name: {first['display_name']}")
    print(f"Works: {first['works_count']}")
    
  5. Try it: What happens if you search for a nonexistent institution like "xyzzy university"? Does the code crash, or does it return an empty list?

Expected outcome: You should see “Carnegie Mellon University” with a works count in the hundreds of thousands.

The Requests Library#

import requests

# GET request
response = requests.get(url, params={'key': 'value'})

# POST request
response = requests.post(url, json={'data': 'value'})

# Response attributes
response.status_code  # 200, 404, etc.
response.json()       # Parse JSON response
response.text         # Raw text
response.headers      # Response headers

OpenAlex API#

OpenAlex is a free, open catalog of scholarly works.

Base URL: https://api.openalex.org

Endpoints#

Endpoint

Description

/works

Scholarly papers

/authors

Researchers

/institutions

Universities, labs

/topics

Topics and fields

# Search for works about machine learning
url = "https://api.openalex.org/works"
params = {
    "search": "machine learning",
    "per_page": 5
}

response = requests.get(url, params=params)
data = response.json()

print(f"Found {data['meta']['count']} works")
for work in data['results']:
    print(f"- {work['title'][:60]}...")
# Get author information
author_url = "https://api.openalex.org/authors"
params = {"search": "John Kitchin"}

response = requests.get(author_url, params=params)
authors = response.json()['results']

if authors:
    author = authors[0]
    print(f"Name: {author['display_name']}")
    print(f"Works count: {author['works_count']}")
    print(f"Citations: {author['cited_by_count']}")

AI-Generated API Code#

Let AI handle the boilerplate:

> Create a function that searches OpenAlex for works by a given author
  and returns a list of dictionaries with title, year, and citation count.
  Include error handling and rate limiting.

Exercise 3: API Exploration with AI (10 min)#

Let’s see how well AI can write API code. Ask your AI agent:

“Write Python code to find the top 5 most-cited papers about ‘density functional theory’ using the OpenAlex API, and print each title with its citation count.”

  1. Run the code the AI gives you. Does it work on the first try?

  2. Examine what the AI did:

    • Which endpoint did it use? (/works)

    • How did it sort by citation count? (look for sort parameter)

    • Did it use params= or build the URL string manually?

    • Did it handle errors?

  3. Extend it: Ask the AI to modify the code to also show the publication year and the journal name (hint: look at primary_location.source.display_name in the API response).

  4. Challenge: Ask the AI — “How would I get the next page of results?” Does it know about OpenAlex pagination (page parameter or cursor pagination)?

Reflect: The AI likely produced working code quickly, but did you understand every line? Could you debug it if the API changed?

# AI-generated function (review carefully!)
import time
from typing import List, Dict

def get_author_works(author_name: str, max_results: int = 25) -> List[Dict]:
    """
    Fetch works by an author from OpenAlex.
    
    Args:
        author_name: Name of the author to search
        max_results: Maximum number of works to return
        
    Returns:
        List of dicts with title, year, and citation_count
    """
    # First, find the author
    author_response = requests.get(
        "https://api.openalex.org/authors",
        params={"search": author_name}
    )
    author_response.raise_for_status()
    
    authors = author_response.json()['results']
    if not authors:
        return []
    
    author_id = authors[0]['id']
    
    # Rate limiting
    time.sleep(0.1)
    
    # Get works by this author
    works_response = requests.get(
        "https://api.openalex.org/works",
        params={
            "filter": f"author.id:{author_id}",
            "per_page": max_results,
            "sort": "cited_by_count:desc"
        }
    )
    works_response.raise_for_status()
    
    works = []
    for work in works_response.json()['results']:
        works.append({
            'title': work.get('title', 'Unknown'),
            'year': work.get('publication_year'),
            'citation_count': work.get('cited_by_count', 0)
        })
    
    return works

Exercise 4: Break It and Fix It (10 min)#

The best way to understand error handling is to cause errors deliberately. Try each of these and observe what happens:

(a) Invalid endpoint — What status code do you get?

response = requests.get("https://api.openalex.org/invalid_endpoint")
print(f"Status code: {response.status_code}")

(b) Impossibly short timeout — What exception is raised?

try:
    response = requests.get("https://api.openalex.org/works", timeout=0.001)
except Exception as e:
    print(f"Exception type: {type(e).__name__}")
    print(f"Message: {e}")

(c) Now write a robust wrapper. Create a function called safe_get that:

  • Takes a URL and optional params

  • Returns the parsed JSON on success

  • Catches Timeout, HTTPError, and general RequestException

  • Prints a helpful message for each error type

  • Returns None on failure instead of crashing

def safe_get(url, params=None, timeout=10):
    # Your code here
    pass

Test your function with the invalid endpoint and the short timeout from above.

Bonus: Ask your AI agent to review your error handling — “Review my safe_get function. Am I missing any edge cases?”

# Test the function
works = get_author_works("John Kitchin", max_results=5)
for work in works:
    print(f"{work['year']}: {work['title'][:50]}... ({work['citation_count']} citations)")

Error Handling#

APIs can fail. Always handle errors:

def safe_api_call(url: str, params: dict = None) -> dict:
    """Make an API call with error handling."""
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.Timeout:
        print("Request timed out")
        return {}
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error: {e}")
        return {}
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
        return {}

Exercise 5: Build an API Wrapper with AI (15 min)#

Use AI to help you build a complete API wrapper function. Ask your AI agent:

“Write a Python function that takes an institution name (e.g., ‘Carnegie Mellon University’), finds the institution in OpenAlex, and returns its top 10 most-cited works with title, year, and citation count. Include error handling and rate limiting.”

After you get the code:

  1. Read through it carefully before running it

  2. Test it with "Carnegie Mellon University"

  3. Test with a misspelled name — does it handle it gracefully?

  4. Test with an empty string — what happens?

Review Checklist#

  • Does it handle “institution not found”?

  • Does it handle API errors (timeouts, bad responses)?

  • Is it rate-limited appropriately?

  • Are the returned fields useful?

  • Did you have to fix anything the AI got wrong?

Reflect: How much time did AI save you? What did you still need to verify yourself?

Summary#

Concept

Key Point

REST APIs

HTTP-based data access

requests library

get(), post(), json()

Error handling

Always use try/except

AI assistance

Great for boilerplate, verify responses

Tips and Tricks#

  • Save API responses to files: response.json() to a file saves tokens — you can share the file instead of re-fetching.

  • Prompt: “Show me how to authenticate to [API name]”: AI usually knows common API auth patterns, but always verify the docs for current endpoints.

  • Use response.status_code checks before parsing: Ask the agent to always include error checking in API code.

  • Prompt: “Parse this JSON and extract [fields]”: AI excels at JSON wrangling — paste a sample response and describe what you need.

  • Rate-limit yourself: Add time.sleep() between requests to avoid being blocked; ask the agent to add this for you.

  • Test with small queries first: Fetch 1-2 results before requesting thousands — saves time and API quota.

  • Keep API keys in environment variables: Ask the agent: “Refactor this code to use environment variables for the API key.”

  • Cache responses during development: Use requests_cache or save to disk so you do not hit the API repeatedly while iterating.

Foundational Concepts to Commit to Memory#

  • REST APIs use HTTP methods: GET retrieves data, POST creates data, PUT updates data, DELETE removes data. Most of your work will be GET requests.

  • Status codes tell you what happened: 200 means success, 404 means not found, 401 means unauthorized, 500 means server error. Check the status code before parsing the response.

  • JSON is the lingua franca of APIs: API responses are almost always JSON. In Python, response.json() parses it into dictionaries and lists you already know how to work with.

  • Query parameters filter and control requests: Use params= in requests.get() rather than building URL strings manually. It handles encoding and is easier to read.

  • Always handle errors: Network requests fail – timeouts, bad URLs, server outages. Wrap API calls in try/except and handle Timeout, HTTPError, and RequestException.

  • Rate limiting is your responsibility: APIs limit how many requests you can make per second. Add time.sleep() between calls or you will get blocked.

  • raise_for_status() converts bad status codes to exceptions: Call it after every request so HTTP errors (4xx, 5xx) become Python exceptions you can catch instead of silent failures.

Knowing vs. Doing: Reflection#

APIs are where the “knowing vs. doing” tension gets very concrete. You can ask an AI agent to write a function that fetches data from OpenAlex, and it will produce working code in seconds – complete with error handling, pagination, and rate limiting. If your goal is to get data for a project, that is a massive win. You just went from zero to a working data pipeline without reading a single page of API documentation.

But consider what happens when something breaks. The API changes its response format. Your requests start returning 429 (rate limited) or 403 (forbidden). The JSON structure has nested fields you did not expect. If you do not understand what HTTP status codes mean, what raise_for_status() actually does, or how query parameters get encoded into URLs, you are stuck. You cannot debug what you do not understand, and AI explanations only help if you have enough context to evaluate whether they are correct. This is the core of it: knowing the fundamentals makes you faster at everything, including using AI effectively.

At the same time, nobody learns APIs by reading documentation cover to cover before writing their first request. You learn by building something – hitting a real endpoint, seeing real data come back, breaking things on purpose, and fixing them. AI agents are ideal partners for this kind of exploratory learning because they can generate the boilerplate while you focus on understanding the concepts. The key is to resist the temptation to treat working code as understood code. Every time AI generates an API call for you, take thirty seconds to read it and make sure you could explain what each line does. That habit is the difference between accumulating real knowledge and just accumulating code you cannot maintain.

Additional Resources#

Next Steps#

In the next module, we’ll package our API code into a distributable Python package.