Ingesting Data from APIs

Pull records from REST APIs with pagination, rate limits and incremental sync for RAG indexes.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 3 · Lesson 4 of 13 · Beginner

Ingesting Data from APIs

Pull records from REST APIs with pagination, rate limits and incremental sync for RAG indexes.

Much of the knowledge a RAG system needs lives behind APIs rather than in files: help-desk tickets, CRM notes, wiki pages, issue trackers, product catalogues. Ingesting from an API means handling authentication, pagination, rate limits and errors, turning JSON records into documents with good text and metadata, and syncing only what changed since the last run. This lesson builds a reusable API ingestion pipeline in Python.

What you will learn

  • How to call a REST API with authentication, timeouts and retries
  • How to handle page-number, cursor and link-header pagination
  • How to respect rate limits
  • How to convert JSON records into RAG documents and sync incrementally

Prerequisites

Installation

pip install requests python-dotenv

Step 1: A robust HTTP session

Every API client needs the same foundations: credentials from the environment, a timeout on every request, and automatic retries for temporary failures. The requests library supports retries through urllib3's Retry:

api_ingest.py
import os
import time

import requests
from dotenv import load_dotenv
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

load_dotenv()

def make_session(token_env: str) -> requests.Session:
    session = requests.Session()
    session.headers.update({
        "Authorization": f"Bearer {os.environ[token_env]}",    # never hard-code tokens
        "Accept": "application/json",
        "User-Agent": "rag-ingestion/1.0",
    })
    retry = Retry(total=5, backoff_factor=1.0,                  # waits about 1, 2, 4, 8 seconds
                  status_forcelist=[429, 500, 502, 503, 504],
                  allowed_methods=["GET"], respect_retry_after_header=True)
    session.mount("https://", HTTPAdapter(max_retries=retry))
    return session

TIMEOUT = (5, 30)        # seconds: connect, read

Status 429 means "too many requests". With respect_retry_after_header=True, urllib3 waits for the time the server's Retry-After header asks for.

Step 2: Handle pagination

APIs return large result sets in pages. The three common styles are page numbers, cursors (a token for the next page) and Link headers. Write one generator per style that yields records, so the rest of the pipeline does not care:

from collections.abc import Iterator

def paginate_pages(session, url: str, params: dict, page_size: int = 100) -> Iterator[dict]:
    """?page=1&per_page=100 style."""
    page = 1
    while True:
        response = session.get(url, params={**params, "page": page, "per_page": page_size}, timeout=TIMEOUT)
        response.raise_for_status()
        items = response.json()
        if not items:
            return
        yield from items
        page += 1

def paginate_cursor(session, url: str, params: dict) -> Iterator[dict]:
    """Response like {"data": [...], "next_cursor": "abc"}; field names vary by API."""
    cursor = None
    while True:
        query = {**params, **({"cursor": cursor} if cursor else {})}
        response = session.get(url, params=query, timeout=TIMEOUT)
        response.raise_for_status()
        body = response.json()
        yield from body["data"]
        cursor = body.get("next_cursor")
        if not cursor:
            return

def paginate_link_header(session, url: str, params: dict) -> Iterator[dict]:
    """GitHub-style Link: <...>; rel="next" headers. requests parses them into response.links."""
    next_url, query = url, params
    while next_url:
        response = session.get(next_url, params=query, timeout=TIMEOUT)
        response.raise_for_status()
        yield from response.json()
        next_url = response.links.get("next", {}).get("url")
        query = None                      # the next URL already contains the query string

Step 3: Throttle proactively

Retries handle rate-limit errors after they happen. It is politer, and faster overall, to stay under the limit. A simple throttle spaces out requests:

class Throttle:
    def __init__(self, requests_per_second: float):
        self.interval = 1.0 / requests_per_second
        self.last = 0.0

    def wait(self) -> None:
        delay = self.last + self.interval - time.monotonic()
        if delay > 0:
            time.sleep(delay)
        self.last = time.monotonic()

Call throttle.wait() before each request. Many APIs also report your remaining quota in response headers (often named like X-RateLimit-Remaining); check your API's documentation.

Step 4: Turn records into documents

JSON records are not good retrieval text as they are. Build readable text from the useful fields, keep identifiers and dates as metadata, and keep the record's URL for citations:

def ticket_to_document(ticket: dict) -> dict:
    """Example for a help-desk ticket; adapt the field names to your API."""
    comments = "\n".join(f"- {c['author']}: {c['body']}" for c in ticket.get("comments", []))
    text = (f"Ticket: {ticket['title']}\n"
            f"Status: {ticket['status']}  Product: {ticket.get('product', 'n/a')}\n\n"
            f"{ticket['description']}\n\nComments:\n{comments}")
    return {
        "id": f"ticket:{ticket['id']}",
        "text": text,
        "metadata": {
            "source": "helpdesk",
            "url": ticket["url"],
            "status": ticket["status"],
            "updated_at": ticket["updated_at"],
        },
    }

Leave out fields that add noise (internal IDs, flags) or personal data you do not need, such as customer emails and phone numbers. See PII Detection and Redaction.

Step 5: Incremental sync

Re-downloading everything on every run is slow and hits rate limits. Most APIs let you ask for records changed since a time (a parameter like updated_since or modified_after). Store the time of the last successful sync and use it next time:

import json
from datetime import datetime, timezone
from pathlib import Path

STATE_FILE = Path("sync_state.json")

def load_state() -> dict:
    return json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}

def save_state(state: dict) -> None:
    STATE_FILE.write_text(json.dumps(state, indent=2))

def sync_tickets(index_documents) -> int:
    """index_documents: your function that chunks, embeds and upserts documents by id."""
    session = make_session("HELPDESK_TOKEN")
    state = load_state()
    started = datetime.now(timezone.utc).isoformat()
    params = {"updated_since": state["tickets"]} if "tickets" in state else {}
    batch, total = [], 0
    for ticket in paginate_cursor(session, "https://helpdesk.example.com/api/tickets", params):
        batch.append(ticket_to_document(ticket))
        if len(batch) == 100:
            index_documents(batch)
            total += len(batch)
            batch = []
    if batch:
        index_documents(batch)
        total += len(batch)
    state["tickets"] = started          # only after the whole sync succeeded
    save_state(state)
    return total

Three details matter. Record the start time, not the end time, so records changed during the run are picked up next time. Save the state only after success, so a failed run is retried in full. And use the record id as the document id, so an updated record replaces its old chunks (see CRUD and Re-indexing). Deleted records need separate handling: use the API's deleted-items endpoint or webhook if it has one, or compare all ids periodically.

Webhooks for near-real-time updates

Many services can call your endpoint when a record changes. A webhook handler should verify the request signature, put the record id on a queue, and return quickly; a worker then fetches the record through the API and re-indexes it. Keep the scheduled incremental sync as a safety net for missed events.

Common errors and troubleshooting

  • 401/403: the token is missing, expired or lacks the scope for this endpoint.
  • The sync never ends: the pagination stop condition is wrong; log the cursor or page number on each request.
  • Duplicate documents: you generated new ids instead of using the record's id.
  • Missing updates: time zone mismatch in updated_since; use UTC ISO 8601 timestamps.

Key takeaways

  • Use a session with credentials from the environment, timeouts and retries with backoff.
  • Wrap each pagination style in a generator that yields records.
  • Convert records into readable text plus metadata, including the URL for citations.
  • Sync incrementally with a saved timestamp and stable document ids, and handle deletions.

Frequently asked questions

Should I use a ready-made connector instead?

Often, yes. LangChain, LlamaIndex and data-integration tools offer loaders for popular services. Check that they support incremental sync, permissions and deletions before relying on them.

How do I keep permissions from the API?

Fetch each record's access information (owners, groups, visibility) and store it as metadata, as described in Access Control.

Practice exercises

  1. Ingest the issues of a public GitHub repository using paginate_link_header.
  2. Add deletion handling by comparing the ids in the index with the ids returned by a full listing.

Related tutorials