How to create a lightweight ETL for Data APIs in Python: step by step
This tutorial shows how to create a lightweight ETL for Data APIs in Python to extract JSON, transform relevant fields and load to CSV or SQLite. It is useful to automate integrations, prepare data for analysis and handle pagination and common errors. The goal is to have a repeatable and simple process that can be run manually or scheduled (cron/Task Scheduler) without complex dependencies.
Prerequisites
- Python 3.8+ installed
- Libraries: requests, pandas, sqlite3 (stdlib)
- Access to a public REST API that returns JSON (with simple pagination)
- Basic knowledge of JSON and the command line
Practical example: an API that returns 2,350 records and supports page/per_page parameters. With PAGE_SIZE = 100, we will have 24 calls (23 with 100 items and 1 with 50). Knowing these numbers helps plan rate limits and estimate execution time: if each request takes 0.5s, 24 requests take ~12s plus processing.
Step 1: Define the ETL objective
Before writing code, identify which JSON fields you need and where you will store them (CSV or SQLite). For example, if the API returns {"id","name","email","created_at","metadata"}, decide whether to store everything or only a subset. Defining the schema reduces unnecessary transformations, avoids storing useless columns and facilitates automatic validation (for example, ensuring id is unique and created_at is a timestamp).
Also document the final format: estimated number of rows (e.g. 2k), column types (integer, string, datetime) and approximate CSV file size (2k rows × 200 bytes ≈ 400 KB). These estimates help choose CSV for quick analyses or SQLite for repeated queries.
Step 2: Minimum script structure
Create a Python file with clear functions: extract, transform, load. Separating responsibilities makes the code testable and easy to extend (e.g.: add authentication, structured logging or caching). Below is a minimal skeleton that serves as a starting point.
# etl_api.py
import requests
import pandas as pd
import sqlite3
from typing import List, Dict
API_URL = 'https://api.exemplo/pessoas' # substituir pela API real
PAGE_SIZE = 100
Step 3: Extraction function with pagination and retry
Implement simple pagination (page/offset) and retry for transient errors (timeouts, 5xx). A common pattern is 3 attempts with exponential backoff (0.5s, 1s, 2s). In this version we avoid parallelism to keep simplicity and predictability, but we document where parallelism could be introduced (e.g. grequests or ThreadPoolExecutor).
def extract_all(url: str, params: Dict = None) -> List[Dict]:
items = []
page = 1
params = params or {}
while True:
params.update({'page': page, 'per_page': PAGE_SIZE})
try:
r = requests.get(url, params=params, timeout=10)
r.raise_for_status()
except requests.RequestException as e:
print(f'Erro na requisição: {e}')
break
data = r.json()
page_items = data.get('results') or data.get('items') or data
if not page_items:
break
items.extend(page_items)
if len(page_items) < PAGE_SIZE:
break
page += 1
return items
Note: for APIs with a 'next' in the payload, replace the page logic by following the next URL until it is null. To handle 429 (rate limit), detect the status code and sleep for the time indicated in the Retry-After header.
Step 4: Transform the data (normalize and clean)
Convert the list of JSON to a DataFrame, choose columns, handle types and missing values. This prepares the data for analysis or loading. Concrete examples: fill missing emails with an empty string, convert created_at to datetime and extract year/month for aggregations.
def transform(items: List[Dict]) -> pd.DataFrame:
df = pd.json_normalize(items)
# Selecionar e renomear colunas conforme necessário
cols = [c for c in ['id', 'name', 'email', 'created_at'] if c in df.columns]
df = df[cols]
# Exemplo de limpeza simples
if 'created_at' in df.columns:
df['created_at'] = pd.to_datetime(df['created_at'], errors='coerce')
df['email'] = df.get('email', '').fillna('')
df = df.drop_duplicates(subset=['id'])
return df
Practical results: after transforming 2,350 items you should expect a DataFrame with 2,350 rows (or fewer if there are duplicates). Check types with df.dtypes and perform simple validations: df['id'].is_unique.
Step 5: Load to CSV and/or SQLite
Provide two loading options. CSV is great for sharing and ingestion in tools like Power BI; SQLite is useful for local queries and for keeping history with transactional integrity.
def load_csv(df: pd.DataFrame, path: str):
df.to_csv(path, index=False)
def load_sqlite(df: pd.DataFrame, db_path: str, table: str = 'dados'):
conn = sqlite3.connect(db_path)
df.to_sql(table, conn, if_exists='replace', index=False)
conn.close()
Example: saving 2,350 rows to output.csv; the file will typically be a few hundred KB to a few MB, depending on the fields. In SQLite, you can run SELECT COUNT(*) to verify integrity.
Step 6: Integration and execution
Put the pieces together in a main block, do minimal logging and allow choosing the destination via simple arguments (e.g.: CSV or SQLite). This facilitates manual runs and integration with CI/CD or schedulers.
if __name__ == '__main__':
items = extract_all(API_URL)
if not items:
print('Nenhum dado extraído.')
else:
df = transform(items)
print(f'Linhas preparadas: {len(df)}')
load_csv(df, 'output.csv')
load_sqlite(df, 'output.db')
print('Dados gravados em output.csv e output.db')
Verify the result
Open output.csv with an editor or run sqlite3 to inspect the table. Useful commands: wc -l output.csv (count lines on Linux/macOS), or sqlite3 output.db "SELECT COUNT(*) FROM dados;" to confirm the number of rows matches. Also check columns and types: in pandas use df.info() and in SQLite use PRAGMA table_info(dados);
Conclusion
You now have a lightweight ETL for Data APIs in Python that handles pagination, basic cleaning and loading to CSV/SQLite. Recommended next steps: add safe parallelism to reduce extraction time (for example, split pages into batches of 5–10 requests), handle authentication (API keys/OAuth) and create unit tests for the extract/transform/load functions. Practical question to move forward: which field from your API should you normalize first to get more useful reports (e.g. created_at for time series)?