import pandas as pd
import urllib.request
url = "https://sta523-fa26.github.io/slides/data/penguins.csv"Lecture 14
Most functions that read from a file path will also accept a URL, downloading the file for you behind the scenes.
(344, 8)
b'species,island,bill_length_mm,bill_depth_mm,flipper_length_mm,body_mass_g,sex,year\n'
This is convenient for a public file at a fixed URL, but there is no way to set headers, authenticate, pass parameters, or handle a failed request. For that we need to work with HTTP directly.
| Component | Description |
|---|---|
| scheme | The protocol to use, usually http or https |
| host | The domain name or IP address of the server |
| port | The port to use, defaults to 80 for http, 443 for https |
| path | Identifies the resource on the server |
| query | Optional key-value pairs |
| fragment | A location within the page, not sent to the server |
Only a limited set of characters may appear in a URL, so spaces and reserved characters like &, /, and ? are percent encoded. These values are usually not part of the host or path but can occur as part of the query string.
Implementations can be inconsistent (e.g. spaces can be encoded as + or %20) but consumers are generally permissive. Both requests and httr2 encode parameter values automatically.
An HTTP request is made up of a method, a URL, headers, and an optional body.
The method, or verb, says what we want done with the resource at the URL.
| Method | Purpose | GitHub API example |
|---|---|---|
GET |
Fetch a resource | Get a user, list org repos |
POST |
Create a new resource | Create a gist, open an issue |
PUT |
Replace a resource | Replace a file in a repo |
PATCH |
Partially update a resource | Update a repo’s description |
DELETE |
Remove a resource | Delete a gist |
GET and POST are by far the most common when consuming APIs.
Loading a page in a browser is a GET, and submitting a form is usually a POST.
An HTTP response contains a status, headers, and an optional body (HTML, JSON, an image, or other content).
The first digit gives the category. 1xx is informational, 2xx is success, 3xx concerns redirection or caching, 4xx a problem with the request, and 5xx a problem on the server.
| Code | Description | Meaning |
|---|---|---|
| 200 | OK | Request succeeded |
| 201 | Created | Resource created, usually after a POST |
| 204 | No Content | Success with no response body |
| 301 | Moved Permanently | Permanent redirect |
| 400 | Bad Request | Malformed request or parameters |
| 401 | Unauthorized | Authentication required or failed |
| 403 | Forbidden | Server refuses access, may also mean rate limited |
| 404 | Not Found | Resource not found or not visible to this client |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server-side failure |
| 503 | Service Unavailable | Server temporarily unavailable |
The code is only a summary. For an error, the response body will usually include a more specific message explaining what went wrong, so it is worth reading.
requestsrequests is the standard third-party Python package for HTTP. A call such as requests.get() builds and sends a request in one step and returns a response object. Its attributes and methods give the status, headers, and parsed body.
httr2Representational State Transfer is an architectural style for web services, not a standard. A RESTful API exposes resources at URLs, called endpoints, and clients work with them using ordinary HTTP.
Resources are addressable. Every resource has its own URL, such as /users/rundel or /orgs/tidyverse/repos.
Requests are stateless. Each request carries everything the server needs to handle it, so nothing is remembered between requests.
The interface is uniform. The standard HTTP methods say what to do and the status codes say how it went.
Resources are returned as representations in the response body. JSON is the most common format, but REST does not require it.
Last lecture we scraped data out of HTML meant for people. APIs provide structured data meant for programs.
GitHub’s REST API exposes nearly everything on the site. We will use it as a running example because it is well documented, mostly public, and the responses are plain JSON.
Endpoints used today,
Get a user, GET /users/{username}
List organization repositories, GET /orgs/{org}/repos
Get the authenticated user, GET /user
Create a gist, POST /gists
Sending the request returns a response. Calling .json() or resp_body_json() then parses its body. Successful JSON parsing alone does not mean the request succeeded.
GitHub still sends a response, with a 404 status and a JSON body describing the problem. httr2 raises an error as soon as it arrives and requests only raises if you call raise_for_status(), but in both cases the response can still be inspected.
A request can be inspected before anything is sent, which is useful for checking that the URL and headers are what we intended.
Parameters are given as a dictionary in Python or as named arguments in R. The libraries add them to the URL and handle the encoding.
| Content | requests |
httr2 |
|---|---|---|
| status code | resp.status_code, resp.ok |
resp_status(), resp_is_error() |
| status text | resp.reason |
resp_status_desc() |
| content type | resp.headers.get("Content-Type") |
resp_content_type() |
| all headers | resp.headers |
resp_headers() |
| one header | resp.headers["X-RateLimit-Limit"] |
resp_header("X-RateLimit-Limit") |
| final URL | resp.url |
resp$url |
Headers carry metadata about the response.
JSON objects become dictionaries in Python and named lists in R.
JSON is the most common response from an API, but the body can be anything. Both libraries expose the raw bytes and the decoded text, and provide parsers for the usual formats.
| Content | requests |
httr2 |
|---|---|---|
| JSON | resp.json() |
resp_body_json(resp) |
| Text | resp.text |
resp_body_string(resp) |
| Raw bytes | resp.content |
resp_body_raw(resp) |
| HTML | BeautifulSoup(resp.text, "html.parser") |
resp_body_html(resp) |
| XML | xml.etree.ElementTree.fromstring(resp.content) |
resp_body_xml(resp) |
| CSV | pd.read_csv(io.StringIO(resp.text)) |
read.csv(text = resp_body_string(resp)) |
| Save to a file | open(path, "wb").write(resp.content) |
req_perform(req, path = path) |
The libraries disagree on the default. httr2 turns a 4xx or 5xx status into an R error, while requests returns the response and leaves checking to you.
Most APIs cap the number of results in one response, so retrieving a large collection means a sequence of requests. There is no single convention, so check the documentation for each API.
Page-based, ?page=2&per_page=30
Offset-based, ?offset=60&limit=30
Cursor-based, each response includes a token that identifies the next batch
Link header, the response’s Link header gives the URL of the next page
GitHub uses page-based parameters and also returns a Link header, so a client can follow the next link until there is none.
requests parses the Link header into the links dictionary, and httr2 provides resp_link_url() to pull out a single relation.
Collect a page, follow its next link, and stop when that link is absent. httr2 provides an iterator for this pattern.
46
['tidyverse/ggplot2',
'tidyverse/lubridate',
'tidyverse/stringr',
'tidyverse/dplyr',
'tidyverse/readr',
'tidyverse/magrittr',
'tidyverse/tidyr',
'tidyverse/nycflights13',
'tidyverse/rvest',
'tidyverse/purrr',
'tidyverse/haven',
'tidyverse/readxl',
'tidyverse/reprex',
'tidyverse/tibble',
'tidyverse/multidplyr',
'tidyverse/dtplyr',
'tidyverse/hms',
'tidyverse/modelr',
'tidyverse/forcats',
'tidyverse/tidyverse',
'tidyverse/tidytemplate',
'tidyverse/blob',
'tidyverse/ggplot2-docs',
'tidyverse/glue',
'tidyverse/style',
'tidyverse/dbplyr',
'tidyverse/googledrive',
'tidyverse/googlesheets4',
'tidyverse/tidyverse.org',
'tidyverse/datascience-box',
'tidyverse/tidyversedashboard',
'tidyverse/dsbox',
'tidyverse/design',
'tidyverse/tidyeval',
'tidyverse/tidy-dev-day',
'tidyverse/funs',
'tidyverse/vroom',
'tidyverse/website-analytics',
'tidyverse/tidyups',
'tidyverse/duckplyr',
'tidyverse/code-review',
'tidyverse/ellmer',
'tidyverse/ragnar',
'tidyverse/vitals',
'tidyverse/ggbot2',
'tidyverse/data-dict']
[1] 46
[1] "tidyverse/ggplot2"
[2] "tidyverse/lubridate"
[3] "tidyverse/stringr"
[4] "tidyverse/dplyr"
[5] "tidyverse/readr"
[6] "tidyverse/magrittr"
[7] "tidyverse/tidyr"
[8] "tidyverse/nycflights13"
[9] "tidyverse/rvest"
[10] "tidyverse/purrr"
[11] "tidyverse/haven"
[12] "tidyverse/readxl"
[13] "tidyverse/reprex"
[14] "tidyverse/tibble"
[15] "tidyverse/multidplyr"
[16] "tidyverse/dtplyr"
[17] "tidyverse/hms"
[18] "tidyverse/modelr"
[19] "tidyverse/forcats"
[20] "tidyverse/tidyverse"
[21] "tidyverse/tidytemplate"
[22] "tidyverse/blob"
[23] "tidyverse/ggplot2-docs"
[24] "tidyverse/glue"
[25] "tidyverse/style"
[26] "tidyverse/dbplyr"
[27] "tidyverse/googledrive"
[28] "tidyverse/googlesheets4"
[29] "tidyverse/tidyverse.org"
[30] "tidyverse/datascience-box"
[31] "tidyverse/tidyversedashboard"
[32] "tidyverse/dsbox"
[33] "tidyverse/design"
[34] "tidyverse/tidyeval"
[35] "tidyverse/tidy-dev-day"
[36] "tidyverse/funs"
[37] "tidyverse/vroom"
[38] "tidyverse/website-analytics"
[39] "tidyverse/tidyups"
[40] "tidyverse/duckplyr"
[41] "tidyverse/code-review"
[42] "tidyverse/ellmer"
[43] "tidyverse/ragnar"
[44] "tidyverse/vitals"
[45] "tidyverse/ggbot2"
[46] "tidyverse/data-dict"
Everything so far has been anonymous. Most APIs give anonymous clients a small rate limit and no access to private resources, and require authentication for anything more.
| GitHub API | Requests per hour | Access |
|---|---|---|
| Unauthenticated | 60 | Public data only |
| Authenticated | Usually 5,000 | Resources allowed by the token |
GitHub accepts a bearer token in the Authorization header, sent as Authorization: Bearer <token>. Other APIs may use API keys, OAuth, or another scheme.
The token identifies you to the API and grants its assigned permissions. Treat it like a password. GitHub rate limits vary by authentication method, and secondary limits also apply.
A personal access token (PAT) is a credential generated on GitHub under Settings > Developer settings > Personal access tokens. Fine-grained tokens scoped to specific repositories and permissions are recommended over classic tokens.
Never put a token in a script, a notebook, or a git repository.
Store it outside the code and read it at run time, from an environment variable, a file such as .env that is ignored by git, or a credential manager.
Give it the minimum permissions needed and an expiration date.
With the token in place, the /user endpoint that failed earlier now returns the account the token belongs to.
When making many requests to the same API, set the shared pieces such as the user agent and token once. In requests a Session carries headers across calls and reuses the connection. In httr2 a request object is a template that can be extended before each req_perform().
Both libraries serialize a dictionary or list as JSON and set the appropriate Content-Type. This example needs a token with permission to write gists (the Gists account permission on a fine-grained token, or the gist scope on a classic one), and creates a public gist on the account the token belongs to.
Creating a gist returns 201 Created. Its response body describes the new resource, including its URL and id.
A successful write can return a different status and body from a successful read, so check the endpoint documentation.
A DELETE request to /gists/{gist_id}, using the id returned when the gist was created, removes it. The response has status 204 No Content and an empty body.
A rate limit usually produces a 429, but some APIs use other 4xx codes (GitHub sometimes returns a 403). Check the headers and message before retrying.
Both permit one request immediately, then one per second. A capacity of 60 would permit a burst of 60 requests. Choose a rate that fits the API.
Transient failures of read requests (a timeout, a 503, a rate limit) are worth retrying after a pause, with the pause growing on each attempt.
httr2 builds this in with req_retry(). The template below allows up to five attempts, waits with exponential backoff, and honors Retry-After.
requests has no retry option of its own. Retries are configured on the underlying urllib3 connection pool by mounting an HTTPAdapter with a Retry object on a Session, which sets the number of attempts, the backoff, and the statuses and methods that qualify. See transport adapters and urllib3.util.Retry.
Using the GitHub API, retrieve every public repository belonging to the posit-dev organization and build a data frame with one row per repository containing its name, primary language, star count, and the date it was last pushed to.
Request type=public and per_page=100, and follow every next-page link. How many repositories and pages are there?
Tabulate the primary language. Treat a missing language as its own category.
Which five repositories were pushed to most recently?
Write a version in Python with requests and a version in R with httr2. Authenticate your requests if you have a token available.
requests and httr2| Task | requests |
httr2 |
|---|---|---|
| GET | requests.get(url) |
request(url) then req_perform() |
| timeout | timeout=10 |
req_timeout(10) |
| query parameters | params={...} |
req_url_query(...) |
| headers | headers={...} |
req_headers(...) |
| bearer token | headers={"Authorization": f"Bearer {t}"} |
req_auth_bearer_token(t) |
| send JSON | requests.post(url, json=...) |
req_body_json(...) |
| other methods | requests.put(), .patch(), .delete() |
req_method() |
| inspect before sending | requests.Request(...).prepare() |
req_dry_run() |
| status | resp.status_code, resp.ok |
resp_status(), resp_is_error() |
| raise on error | resp.raise_for_status() |
default, disable with req_error() |
| parse JSON | resp.json() |
resp_body_json() |
| headers | resp.headers |
resp_headers(), resp_header() |
| pagination | resp.links["next"]["url"] in a loop |
req_perform_iterative(), resps_data() |
| shared settings | requests.Session() |
a request object used as a template |
| throttle / retry | time.sleep(), urllib3.util.Retry |
req_throttle(), req_retry() |
HTTP is a request with a method, URL, headers, and body, answered by a response with a status, headers, and body. Everything on the web, including scraping and APIs, is built on this exchange.
A REST API exposes resources at URLs using HTTP methods and representations such as JSON. The status code says whether it worked and the JSON body carries the result.
requests does each request in a single function call, while httr2 builds a request object and then performs it. Both give back a response object with the status, headers, and methods for parsing the body.
Check the status. httr2 errors by default and requests does not, so call raise_for_status() before parsing. Set a timeout as well.
Large collections come back a page at a time. Follow the Link header or page parameters until the results run out.
Authenticate with a token kept out of your code, respect rate limits, and be careful with any request that is not a GET.
Sta 523 - Fall 2026