12.1. API Fundamentals: GET, Params, and Error Handling#

Hide code cell source

import json
from urllib.parse import urlparse, parse_qs

import requests

Web APIs let Python programs request data from services over HTTP. In data work, an API is often the difference between copying a file by hand and writing a repeatable data collection step. This section focuses on read-only API calls: choosing an endpoint, passing query parameters, reading JSON, and handling errors without crashing a larger analysis.

12.1.1. What Is an API?#

An application programming interface (API) is a defined way for one program to request a service from another program. You have already used several kinds. In each case, you follow the documented rules for making a request and never need to see how the work is done.

  • A library API is the set of functions and classes a package provides, such as math.sqrt() or the methods of a pandas DataFrame.

  • An operating system API lets a program ask the system to open a file, read the clock, or draw a window, which is what open() does on your behalf.

  • A database API lets a program send queries and receive rows.

A web API applies the same idea across a network. The program making the request is the client, and the program that answers is the server. They communicate using HTTP (Hypertext Transfer Protocol), the same protocol browsers use to load web pages. Most web APIs follow a convention called REST, in which each URL identifies a resource, such as a customer or a weather forecast, and the HTTP method indicates what action the client wants to take on it.

Method

Purpose

Example request

Typical success

Safe

Idempotent

GET

Retrieve one resource or a list

GET /weather?city=Rolla

200 OK

Yes

Yes

POST

Create a resource or submit data for processing

POST /saved-cities with {"city": "Rolla"}

201 Created

No

No

PUT

Create or replace a whole resource

PUT /saved-cities/42 with the full record

200 OK, 204 No Content, or 201 Created

No

Yes

PATCH

Change part of a resource

PATCH /saved-cities/42 with {"units": "celsius"}

200 OK or 204 No Content

No

Not guaranteed

DELETE

Remove a resource

DELETE /saved-cities/42

204 No Content

No

Yes

A safe method does not request changes to server state; incidental effects, such as request logging, may still occur. An idempotent (idem, “same”; potent, “power”) method has the same intended effect on the server whether you send the same request once or several times: deleting record 42 twice still leaves it deleted, but posting the same city twice can create two saved records.

Idempotence describes the effect on the server, not the response. The first DELETE might return 204 No Content, while a repeat returns 404 Not Found. The distinction matters when a request times out and your code retries it, which 12.2 API Reliability covers.

A REST API documentation also mentions two more methods, both safe and idempotent: HEAD works like GET but returns only the response headers, and OPTIONS asks which methods an endpoint accepts.

This section uses only GET. The other methods appear here so you can read API documentation, and they return in the next section.

Every HTTP response begins with a status code, a three-digit number the server uses to report how the request went. Your code should check it before trusting anything else in the response, because a server can send back a well-formed body that describes an error instead of the data you asked for. You have probably seen one already: 404 Not Found, the code behind a broken link.

The first digit gives the category, and it tells you who needs to act. A code starting with 2 means the request succeeded. A code starting with 4 means something was wrong with the request, so sending it again unchanged will fail the same way. A code starting with 5 means the server failed on a valid request, so trying again later may work. You do not need to memorize individual codes; knowing the ranges is enough to decide what to do next:

Code range

Meaning

Typical action

2xx

Success

Parse the response

3xx

Redirect

Usually handled by the client library

4xx

Client-side problem

Check the endpoint, parameters, or authentication; for 429 Too Many Requests, wait and retry

5xx

Server-side problem

Retry later or report failure gracefully

A useful habit is to describe every API call as endpoint + method + parameters + expected response shape.

12.1.1.1. Worked Example: Read an API Contract#

Open-Meteo is a free weather API that needs no key. Its documentation describes a request for the current weather like this:

#

Field

Value

1

Endpoint

https://api.open-meteo.com/v1/forecast

2

Method

GET

3

Required params

latitude, longitude

4

Optional param used here

current_weather=true

5

Response

JSON object with latitude, longitude, and a nested current_weather object that holds temperature, windspeed, and more

Before writing code, identify the smallest successful request and the keys your code expects back.

api_contract = {
    "endpoint": "https://api.open-meteo.com/v1/forecast",
    "method": "GET",
    "required_params": ["latitude", "longitude"],
    "response_keys": ["latitude", "longitude", "current_weather"],
}

print(api_contract["method"], api_contract["endpoint"])
print("Required params:", ", ".join(api_contract["required_params"]))
print("Expected keys:", ", ".join(api_contract["response_keys"]))
GET https://api.open-meteo.com/v1/forecast
Required params: latitude, longitude
Expected keys: latitude, longitude, current_weather

You can check the contract against the live service. The cell below sends the smallest successful request for Rolla, Missouri, with requests.get() from the next section, and compares the keys that come back with the contract. It runs on its own, needs an internet connection, and is skipped when the book builds, so press Run to see a live response. If the request fails, it prints a message instead of an error.

import requests

try:
    response = requests.get(
        api_contract["endpoint"],
        params={"latitude": 37.95, "longitude": -91.77, "current_weather": "true"},
        timeout=10,
    )
    response.raise_for_status()	# checks the status code of a response: 2xx, ...
    live = response.json()		
    print("Top-level keys:", ", ".join(sorted(live)))
    print("Contract keys present:", all(key in live for key in api_contract["response_keys"]))
    print("Current temperature:", live["current_weather"]["temperature"],
          live["current_weather_units"]["temperature"])

except requests.RequestException as error:
    print("Request failed:", error)


### response.raise_for_status() checks the response’s status code and raises an exception if it signals an error (4xx or 5xx).
### response.json() takes the body of the response, which arrives as JSON text, and converts it into ordinary Python objects, so live is a dictionary you can index.

A run in November 2026 printed the lines below. The contract keys are all there, along with extras such as timezone and current_weather_units that this request does not need. Your temperature will differ.

Top-level keys: current_weather, current_weather_units, elevation, generationtime_ms, latitude, longitude, timezone, timezone_abbreviation, utc_offset_seconds
Contract keys present: True
Current temperature: 7.5 °C
### Exercise: Describe an Endpoint
#   The documentation for a forecast endpoint says: send a GET request to
#   https://api.example.test/forecast with the required parameters `city` and
#   `days`; the response is a JSON object with the keys `city` and `daily`.
#   Build a dictionary `forecast_contract` with the keys "endpoint", "method",
#   "required_params", and "response_keys", as in the worked example, and print
#   it in the same three-line format.
#   Print exactly:
#   GET https://api.example.test/forecast
#   Required params: city, days
#   Expected keys: city, daily
### Your code starts here



### Your code ends here

Hide code cell source

### Solution
forecast_contract = {
    "endpoint": "https://api.example.test/forecast",
    "method": "GET",
    "required_params": ["city", "days"],
    "response_keys": ["city", "daily"],
}

print(forecast_contract["method"], forecast_contract["endpoint"])
print("Required params:", ", ".join(forecast_contract["required_params"]))
print("Expected keys:", ", ".join(forecast_contract["response_keys"]))
GET https://api.example.test/forecast
Required params: city, days
Expected keys: city, daily

12.1.2. Making GET Requests with requests#

The requests library is the common Python tool for HTTP. A basic GET request looks like this:

response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()

requests provides a convenience function for each common HTTP method (get, post, put, patch, delete, head, options). Each is a thin wrapper around the general requests.request(method, url, **kwargs), so requests.get(url) is equivalent to requests.request("GET", url).

The cell below sends the same GET request both ways to httpbin.org, a free service that echoes back what it receives, and compares the results. It calls a live service, so the book skips it during the build; run it yourself. If the request fails, it prints a message instead of an error.

import requests

url = "https://httpbin.org/get"
params = {"q": "python"}

try:
    r1 = requests.get(url, params=params, timeout=10)
    r2 = requests.request("GET", url, params=params, timeout=10)
    
    r1.raise_for_status()
    r2.raise_for_status()
    
    print("r1:", r1.request.method, r1.url, r1.status_code)
    print("r2:", r2.request.method, r2.url, r2.status_code)
    print("Server saw the same query:", r1.json()["args"] == r2.json()["args"])
    print("Separate response objects:", r1 is not r2)

except requests.RequestException as error:
    print("No live connection:", error)
    
    
### .json() parses the response body into a dictionary, and ["args"] immediately pulls out the value stored under the key "args".

A run in November 2026 printed:

r1: GET https://httpbin.org/get?q=python 200
r2: GET https://httpbin.org/get?q=python 200
Server saw the same query: True

Both calls built the same URL, and the server received the same query, but each call sent a separate request and returned its own response object.

The core examples in this chapter use stand-ins instead of the network, so they run the same way every time, online or not. A few optional cells, such as the contract check at the start of this section and the httpbin comparison above, call a real service. The book skips them when it builds, so run them yourself to see a live response.

12.1.2.1. Worked Example: Parse a JSON Response#

This example uses a small stand-in for a requests response, so it runs without a network connection. The stand-in has the same raise_for_status() and .json() methods as a real response, so the parsing code is exactly what you would write against a live API.

import requests

class DemoResponse:
    def __init__(self, payload, status_code=200):
        self._payload = payload
        self.status_code = status_code

    def raise_for_status(self):
        if self.status_code >= 400:
            raise requests.HTTPError(f"HTTP {self.status_code}")

    def json(self):
        return self._payload

response = DemoResponse({"city": "Rolla", "temperature": 72.5, "units": "fahrenheit"})
response.raise_for_status()
data = response.json()

print(f"{data['city']}: {data['temperature']} degrees {data['units']}")
Rolla: 72.5 degrees fahrenheit
### Exercise: Read a Response
#   Use `DemoResponse`, the stand-in from the worked example above. Create
#   `response` from `city_payload`, call `raise_for_status()`, and parse the
#   body with `.json()`. Then print how many cities the payload lists and the
#   name of the first one.
#   Print exactly:
#   3 cities
#   First: Rolla
city_payload = {"results": [{"name": "Rolla"}, {"name": "Austin"}, {"name": "Boston"}]}
### Your code starts here



### Your code ends here

Hide code cell source

### Solution
city_payload = {"results": [{"name": "Rolla"}, {"name": "Austin"}, {"name": "Boston"}]}

response = DemoResponse(city_payload)
response.raise_for_status()
data = response.json()

print(len(data["results"]), "cities")
print("First:", data["results"][0]["name"])
3 cities
First: Rolla

12.1.3. JSON Text and Python Objects#

An API sends its response body over the network as text. JSON (JavaScript Object Notation) looks a lot like Python dictionary and list literals, but until something parses it, a JSON body is just a string. The standard library json module converts in both directions:

Function

Input

Output

json.loads(text)

A JSON string

Python dict, list, str, int, float, bool, or None

json.dumps(obj)

A Python dict, list, or other basic value

A JSON string

The s at the end of each name stands for string. Turning Python objects into JSON text is called JSON serialization, and parsing the text back is deserialization. response.json() is a shortcut for the parsing step: it takes the response body text and calls json.loads() on it for you. When JSON text comes from somewhere other than a requests response, such as a saved string, a log line, or a cache, you call json.loads() yourself.

A response gives you three ways to read its body:

Attribute

Gives you

Use for

response.text

The body as a str

Looking at the raw text, HTML pages

response.content

The body as bytes

Images, files, anything binary

response.json()

The body parsed into a dict or list

JSON APIs

response.json() is a method, so it needs the parentheses; response.text and response.content are plain attributes. Calling response.json() gives the same result as json.loads(response.text).

JSON and Python spell a few values differently:

JSON

Python

"text" (double quotes only)

'text' or "text"

true, false

True, False

null

None

number

int or float

object {...}

dict

array [...]

list

12.1.3.1. Worked Example: Parse JSON Text by Hand#

The string below stands in for a response body. It contains false and null, so it is valid JSON but not valid Python. After json.loads(), you work with an ordinary dictionary, and .get() supplies a default for a key the payload does not include.

import json

raw_body = '{"city": "Rolla", "temperature": 72.5, "raining": false, "alerts": null}'
print(type(raw_body))

weather = json.loads(raw_body)
print(type(weather))
print(weather["raining"], weather["alerts"])
print(weather.get("humidity", "not reported"))
<class 'str'>
<class 'dict'>
False None
not reported

Going the other way, json.dumps() turns a Python object into JSON text, for example to log a summary, save it to a file, or send it in a request body. In the output, False becomes false, None becomes null, and every string uses double quotes. Parsing that text again gives back an equal dictionary.

summary = {"city": weather["city"], "raining": weather["raining"], "alerts": weather["alerts"]}
summary_text = json.dumps(summary)

print(summary_text)
print(type(summary_text))
print(json.loads(summary_text) == summary)
{"city": "Rolla", "raining": false, "alerts": null}
<class 'str'>
True
### Exercise: JSON Round Trip
#   `request_options` is a Python dictionary that a program wants to store as
#   JSON text. Before you run any code, predict how `False` and `None` will
#   appear in the JSON text. Then convert the dictionary to a JSON string named
#   `options_text` with `json.dumps()` and print it. Finally, parse
#   `options_text` with `json.loads()` and print whether the result equals
#   `request_options`.
#   Print exactly:
#   {"city": "Rolla", "units": "metric", "include_alerts": false, "max_days": 3, "station": null}
#   True
request_options = {"city": "Rolla", "units": "metric", "include_alerts": False, "max_days": 3, "station": None}

### Your code starts here

### Your code ends here

Hide code cell source

### Solution
request_options = {"city": "Rolla", "units": "metric", "include_alerts": False, "max_days": 3, "station": None}

options_text = json.dumps(request_options)
print(options_text)
print(json.loads(options_text) == request_options)
{"city": "Rolla", "units": "metric", "include_alerts": false, "max_days": 3, "station": null}
True

12.1.4. Query Parameters#

Many GET endpoints use query parameters: key/value pairs after the ? in a URL. Build them with the params= argument instead of manually concatenating strings. requests handles escaping spaces, punctuation, and special characters correctly.

12.1.4.1. Worked Example: Build a Request URL Safely#

Instead of sending the request, this example prepares it and prints the URL that requests builds from params=. Notice that the space in New York is encoded for you, and that parsing the query string recovers the original values.

from urllib.parse import urlparse, parse_qs		# “parse query string”

import requests

base_url = "https://api.example.test/weather"
params = {"city": "New York", "units": "fahrenheit"}

request = requests.Request("GET", base_url, params=params).prepare()
print(request.url)

parsed = urlparse(request.url)
print(parse_qs(parsed.query))


### .prepare() builds the final, ready-to-send version of a request without sending it.
https://api.example.test/weather?city=New+York&units=fahrenheit
{'city': ['New York'], 'units': ['fahrenheit']}

Behind params=, requests performs URL encoding, also called percent-encoding: a character with special meaning in a URL is replaced by % followed by its byte value in hexadecimal. The standard library function urllib.parse.urlencode() does the same job for a whole dictionary, and urllib.parse.quote() encodes a single value. A space becomes + in urlencode() output and %20 in quote() output, and servers read both as a space in a query string. Characters such as & and = are escaped as %26 and %3D, so a value that contains them cannot split the query string into extra parameters. The first line below joins raw values by hand and shows the problem: the server would read fish & chips as two parameters. You rarely call these functions yourself, because requests does this for you with params=.

from urllib.parse import urlencode, quote

search_params = {"q": "fish & chips", "filter": "price=low", "city": "New York"}

naive = "&".join(f"{key}={value}" for key, value in search_params.items())
print(naive)
print(urlencode(search_params))
print(quote("fish & chips"))
q=fish & chips&filter=price=low&city=New York
q=fish+%26+chips&filter=price%3Dlow&city=New+York
fish%20%26%20chips

Every parameter value ends up as text in the URL. requests turns a Python True into the text True, but most web APIs, Open-Meteo included, document the lowercase JSON spelling true. That is why the Open-Meteo request at the start of this section passes "current_weather": "true" as a string.

### Exercise: Query Parameters
#   The endpoint https://api.example.test/search accepts `q`, `page`, and
#   `limit`. Create a prepared GET request for page 2 of a search for
#   `python api`, limited to 5 results, and print the final URL.
#   Print exactly:
#   https://api.example.test/search?q=python+api&page=2&limit=5
### Your code starts here
search_url = "https://api.example.test/search"
params = {
    # Fill in q, page, and limit.
}

prepared = requests.Request("GET", search_url, params=params).prepare()
print(prepared.url)
### Your code ends here
https://api.example.test/search

Hide code cell source

### Solution
search_url = "https://api.example.test/search"
params = {"q": "python api", "page": 2, "limit": 5}

prepared = requests.Request("GET", search_url, params=params).prepare()
print(prepared.url)
https://api.example.test/search?q=python+api&page=2&limit=5

12.1.5. Error Handling#

Two categories of errors matter in most API code:

  1. Network errors: timeouts, DNS failures, broken connections, or other exceptions raised before a response arrives.

  2. HTTP errors: the server responds, but the status code signals a problem, such as 404 Not Found or 500 Internal Server Error.

A reliable API helper should use a timeout, call raise_for_status(), and return a predictable value when the request fails.

12.1.5.1. Worked Example: Safe JSON Fetching#

This example wraps both failure checks in one function. raise_for_status() turns an error status into a requests.HTTPError, and .json() raises a ValueError when the body is not valid JSON, for example when a server under maintenance returns an HTML page instead. TextResponse extends the stand-in with a raw text body, as a real response has, so you can see that second case. Either way, the function returns None instead of crashing.

import json

import requests

class TextResponse(DemoResponse):
    """A response stand-in that holds the raw body text, like a real response."""

    def __init__(self, text, status_code=200):
        super().__init__(None, status_code)
        self.text = text

    def json(self):
        return json.loads(self.text)

def parse_json_response(response):
    """Return JSON data from a response-like object, or None if it fails."""
    try:
        response.raise_for_status()
        return response.json()
    except requests.HTTPError as error:
        print("HTTP error:", error)
    except ValueError as error:
        print("Invalid JSON:", error)
    return None

ok = DemoResponse({"results": ["a", "b"]}, status_code=200)
missing = DemoResponse({"message": "not found"}, status_code=404)
html_page = TextResponse("<html>Down for maintenance</html>")

print(parse_json_response(ok))
print(parse_json_response(missing))
print(parse_json_response(html_page))
{'results': ['a', 'b']}
HTTP error: HTTP 404
None
Invalid JSON: Expecting value: line 1 column 1 (char 0)
None

12.1.5.2. Catching Any Request Failure#

The requests library organizes its exceptions in a hierarchy. requests.RequestException is the base class, and about 20 specific errors inherit from it:

  • requests.ConnectionError (the server cannot be reached),

  • requests.Timeout (no reply arrives within the timeout limit), and

  • requests.HTTPError (raised by raise_for_status()).

Such as:

class ConnectionError(RequestException):
    """A Connection error occurred."""

Because every one of them is a RequestException, the clause except requests.RequestException catches any request failure. Use it when your code handles every failure the same way, and catch a specific subclass such as requests.HTTPError first when one case needs its own handling.

try:
    response = requests.get(url, timeout=5)
    response.raise_for_status()
except requests.RequestException as error:
    print("Request failed:", error)

With a real response, a body that is not valid JSON makes .json() raise requests.JSONDecodeError, which is both a ValueError and a RequestException, so this clause catches it too. The TextResponse stand-in raises the standard library’s json.JSONDecodeError, which is only a ValueError; that is why parse_json_response() catches ValueError.

The stand-in function below raises requests.Timeout instead of making a real call, so you can watch the base class catch it without a network connection.

import requests

def fake_get(url, timeout):
    """Stand in for requests.get() by simulating a server that never replies."""
    raise requests.Timeout(f"No reply from {url} within {timeout} seconds")

def safe_get(url):
    try:
        return fake_get(url, timeout=5)
    except requests.RequestException as error:
        print(f"{type(error).__name__}: {error}")
        return None

print(issubclass(requests.Timeout, requests.RequestException))
print(issubclass(requests.HTTPError, requests.RequestException))
print(safe_get("https://api.example.test/data"))
True
True
Timeout: No reply from https://api.example.test/data within 5 seconds
None
### Exercise: Name the Failure
#   Complete `describe_failure(call_fn)`. It calls `call_fn()` and returns
#   "ok" when no exception occurs. Otherwise it returns "timeout" for
#   `requests.Timeout`, "http error" for `requests.HTTPError`, and
#   "other request error" for any other `requests.RequestException`.
#   Order the `except` clauses so each specific subclass is caught before
#   the base class.
#   Print exactly:
#   ok
#   timeout
#   http error
#   other request error
def succeed():
    return {"status": "ok"}

def time_out():
    raise requests.Timeout("no reply")

def not_found():
    raise requests.HTTPError("HTTP 404")

def refuse():
    raise requests.ConnectionError("connection refused")

def describe_failure(call_fn):
    ### Your code starts here
    return "ok"
    ### Your code ends here

for call_fn in [succeed, time_out, not_found, refuse]:
    print(describe_failure(call_fn))
ok
ok
ok
ok

Hide code cell source

### Solution
def succeed():
    return {"status": "ok"}

def time_out():
    raise requests.Timeout("no reply")

def not_found():
    raise requests.HTTPError("HTTP 404")

def refuse():
    raise requests.ConnectionError("connection refused")

def describe_failure(call_fn):
    try:
        call_fn()
    except requests.Timeout:
        return "timeout"
    except requests.HTTPError:
        return "http error"
    except requests.RequestException:
        return "other request error"
    return "ok"

for call_fn in [succeed, time_out, not_found, refuse]:
    print(describe_failure(call_fn))
ok
timeout
http error
other request error

12.1.6. Exercises#

This task combines query parameters, JSON parsing, error handling, and nested payloads from this section.

### Exercise: Weather Request Helper
#   1. Prepare a GET request to https://api.open-meteo.com/v1/forecast with the
#      params latitude=37.95, longitude=-91.77, and current_weather="true", and
#      print its URL.
#   2. Write `weather_from_response(response)`. It parses the response with
#      `parse_json_response()` from the Error Handling section and returns a
#      dict with the temperature and wind speed. It returns None when parsing
#      fails or when the payload has no "current_weather" key.
#   3. Call it on the four `TextResponse` stand-ins below and print each result.
#   Print exactly:
#   https://api.open-meteo.com/v1/forecast?latitude=37.95&longitude=-91.77&current_weather=true
#   {'temperature': 21.4, 'windspeed': 13.2}
#   HTTP error: HTTP 503
#   None
#   Invalid JSON: Expecting value: line 1 column 1 (char 0)
#   None
#   None
responses = [
    TextResponse('{"latitude": 37.95, "current_weather": {"temperature": 21.4, "windspeed": 13.2}}'),
    TextResponse('{"reason": "busy"}', status_code=503),
    TextResponse("<html>Down for maintenance</html>"),
    TextResponse('{"error": "Latitude must be in range of -90 to 90"}'),
]
### Your code starts here



### Your code ends here

Hide code cell source

### Solution
responses = [
    TextResponse('{"latitude": 37.95, "current_weather": {"temperature": 21.4, "windspeed": 13.2}}'),
    TextResponse('{"reason": "busy"}', status_code=503),
    TextResponse("<html>Down for maintenance</html>"),
    TextResponse('{"error": "Latitude must be in range of -90 to 90"}'),
]

params = {"latitude": 37.95, "longitude": -91.77, "current_weather": "true"}
request = requests.Request("GET", "https://api.open-meteo.com/v1/forecast", params=params).prepare()
print(request.url)

def weather_from_response(response):
    payload = parse_json_response(response)
    if payload is None or "current_weather" not in payload:
        return None
    current = payload["current_weather"]
    return {"temperature": current["temperature"], "windspeed": current["windspeed"]}

for response in responses:
    print(weather_from_response(response))
https://api.open-meteo.com/v1/forecast?latitude=37.95&longitude=-91.77&current_weather=true
{'temperature': 21.4, 'windspeed': 13.2}
HTTP error: HTTP 503
None
Invalid JSON: Expecting value: line 1 column 1 (char 0)
None
None