How to consume an API with Python for data: from request to DataFrame
Consuming an API with Python for data work comes down to three things in sequence: fetch the JSON with a request, handle pagination and network failures, and convert the result into a DataFrame that is ready for analysis. The walkthrough below is written for a routine that runs again next week, not for a script you throw away.
What needs to be in place before the first request?
Read the endpoint documentation before writing code: HTTP method, base URL, required parameters, response shape, and how authentication works. The API key is a credential, so it belongs in an environment variable or a file outside version control, never typed into the script.
On the machine you need Python installed, an editor or Jupyter Notebook, and the requests and pandas libraries. The notebook is where you explore the response and understand its shape; a .py script is what runs on a schedule once you know the shape.
Keep collection and processing as two separate steps. Collection only fetches and stores the raw JSON. Processing reads what was stored and builds the DataFrame. When collection fails you do not lose your cleaning logic, and when the cleaning logic changes you do not hit the API again.
- Confirm the base URL, the endpoint version, and the required parameters in the documentation
- Store tokens and keys in environment variables, never in the repository
- Check whether the response is JSON and whether fields are nested
- Write down the request limit the service itself documents
- Decide the date window and the minimum set of fields the analysis actually uses
How do you make the request and read the JSON without errors?
The basic call is `requests.get(url, headers=headers, params=params, timeout=30)`. The timeout matters: without it a stalled connection can eat the whole runtime of the routine. Filters such as date ranges and page numbers go in `params`, which keeps the URL readable and easy to change.
Check `response.status_code` before calling `.json()`. Not every response is JSON — a gateway error often comes back as HTML, and the parser fails with a message that points you to the wrong place. Verifying status and `Content-Type` first keeps debugging where the problem actually is.
`response.json()` returns a dict or a list. Instead of printing the whole payload, inspect the type, the first-level keys, and the length of the record list. That tells you whether the useful data sits at the root or inside a key such as `results` or `data`.
- Build the authentication headers once and reuse them
- Pass filters through `params` instead of concatenating strings into the URL
- Set an explicit timeout on every call
- Validate status and content type before parsing
- Print only type, keys, and record count to understand the structure
How do you page through results without losing or duplicating records?
Three pagination patterns are common: offset and limit, a cursor or continuation token, and a next-page link in the headers. The service documentation states which one applies, and the loop should follow that pattern rather than guess it.
Give the loop an explicit stop condition: an empty page, a missing next cursor, or a maximum page counter as a safety net. Saving each raw page to disk before processing is what lets you reprocess later without repeating the collection.
Duplicates happen when the dataset changes during collection and one record appears on the boundary between two pages. Deduplicating on the record identifier and keeping the most recent version resolves most of these cases.
If the record order is not stable, the output can differ between runs. Pinning a sort parameter, when the service offers one, makes the collection reproducible.
- Identify the pagination pattern in the documentation
- Define the stop condition before writing the loop
- Save each page's JSON with the page number and collection timestamp
- Drop duplicates by record id
- Record the sort order used so the collection can be repeated
How do you handle errors and rate limits in a recurring routine?
Errors fall into two groups. Credential, permission, parameter, and not-found errors will not fix themselves by retrying — the request has to change. Rate-limit responses and temporary server failures can be retried after a wait.
For the second group, use retries with growing waits between attempts and respect the wait time header when the service sends one. Retrying immediately at fixed short intervals usually makes a block worse.
Handle errors per request, not per batch. One failing page should not discard the pages already stored. Log the URL, the status code, and a short body excerpt for every failure, and let the routine finish with a summary of what was collected and what was skipped.
The same discipline applies to the response body: a 200 status with an empty record list is not an error, but it may mean the date window is wrong. Treating empty and failed as the same event hides a real problem.
- Separate errors that need a code fix from errors that can be retried
- Cap the number of retries and the total wait per request
- Respect the wait time header when the service provides one
- Log status, URL, and a short body excerpt for each failure
- Distinguish an empty result from a failed request
How do you turn the JSON into a DataFrame you can analyze?
For a flat list of records, `pd.DataFrame(records)` is enough. For nested payloads, `pd.json_normalize` with `record_path` and `meta` flattens the list you care about while keeping the parent fields beside it. Choose one level of flattening and keep the rest as object columns rather than exploding every key at once.
After loading, set dtypes explicitly. Identifiers that look numeric often must stay as strings, dates need `pd.to_datetime` with an explicit format or `utc=True`, and numeric columns that arrive as text need conversion with `errors='coerce'` so bad values become nulls instead of crashing the load.
Add the collection timestamp as a column. In a routine that runs repeatedly, that column is what lets you compare snapshots and detect records that stopped appearing. This is the same preparation work — cleaning, type handling, outlier checks — that shows up in any analysis pipeline, and it is where most of the time goes.
- Use `pd.DataFrame` for flat lists and `pd.json_normalize` for nested payloads
- Set dtypes explicitly instead of accepting inferred types
- Parse dates with an explicit format or as UTC
- Convert numeric text with `errors='coerce'`
- Add a collection timestamp column for snapshot comparison
What makes the routine hold up week after week?
A recurring pipeline needs three habits: idempotent writes (running it twice does not double the rows), a stored raw layer you can replay from, and a small log of rows collected, rows dropped as duplicates, and pages that failed. With those in place, a break is diagnosable in minutes.
Testing matters more than it seems. Run the transformation against a saved JSON file before pointing it at the live endpoint, so you separate API problems from code problems. Then keep a fixed sample response in the repository as a regression test.
If you are assembling these pieces for the first time, the Python for Data Science and Analytics course at python.paanalytics.net covers the foundation from zero: IDE and Jupyter Notebook setup, basic functions, NumPy and Pandas, user-defined functions, loops and conditionals, data cleaning and preparation, visualization, and outlier detection. The three main modules — Basic, Intermediate, and Advanced — plus bonus modules also cover machine learning, including linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation, and the course closes with an end-to-end final project in exploratory analysis and machine learning. Lessons are recorded and watched at your own pace, with guided exercises, real market projects for a portfolio, a completion certificate, an exclusive community, permanent access with no expiry date, and no prior programming required. The price is R$ 470, or 12 installments of R$ 20.37 on a card, paid through the Hotmart checkout, which also accepts boleto.
- Make writes idempotent so a rerun does not duplicate rows
- Keep the raw JSON layer so you can replay without re-fetching
- Log collected rows, duplicates dropped, and failed pages
- Test the transformation against a saved sample before the live endpoint
- Schedule the collection separately from the analysis
See the Python for Data Science and Analytics course
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Do I need an API key for a public endpoint?
It depends on the service. Some public endpoints need no key but apply a lower request limit; others require a key even for read-only access. The documentation for that specific API is the only place that answers it — and whatever the answer, keep the key out of the repository.
Should I use requests or an official client library for the API?
An official client often handles authentication and retries for you, which saves code when the service offers one. requests is general-purpose and works with any HTTP endpoint, but you write the pagination and retry logic yourself. Either way, the timeout and the status check stay your responsibility.
How often should the collection run?
As often as the source data changes and the documented request limit allows. A dataset updated once a day does not need an hourly collection, and running more often than the source changes only burns quota and adds duplicate work.
What do I do when the JSON is too nested to normalize cleanly?
Flatten the level that carries the records and keep deeper structures as object columns. You can also normalize in two passes, joining the parent and child tables on the record id. Exploding every key in one call usually produces a wide table you cannot reason about.
Can I skip saving the raw JSON and work only with the DataFrame?
You can, but you lose the ability to reprocess without calling the API again. Keeping the raw layer costs disk space and saves a full re-collection every time the transformation logic changes or a field turns out to be missing.