Consuming real REST APIs: pagination, authentication, rate limiting and errors

Page 3 of 15 · Python, NETCONF & RESTCONF · All pages ↓

THEORY · TH-PY-003

RESTCONF on a single router is a gentle API: one user, one device, small answers. The controller and cloud APIs that a Cisco automation solution also consumes (Meraki Dashboard, Catalyst Center, Catalyst SD-WAN Manager) are different. They return thousands of objects in pages, hand out tokens that expire, count your calls per second and answer with their own error formats. AUTOCOR topic 1.6 asks for a solution that consumes REST APIs “including extended API attributes”: pagination, complex authentication workflows, rate limiting, error handling and persistent authentication. This page takes each of those, shows how the Cisco documentation describes it, and ends with a small client, tested against a simulated API, that handles all of them.

BLUEPRINT · AUTOCOR 350-901 v2.0: 1.6 · CCIE Automation v1.2: 2.3

Jump to: Read the documentation first · Authentication patterns · Persistent authentication · Pagination · Rate limiting · Error handling · A client that puts it together · What the exam expects · Exam check · References

Prerequisites: TH-PY-002 (sessions, timeouts, retries and idempotency with requests).

What you will be able to do after this page

  • Read a new API’s documentation and extract what the client must handle (CCIE 2.3).
  • Implement the four authentication patterns used by Cisco platforms: static key, token exchange, session cookie with XSRF token, and OAuth 2.0 / JWT bearer tokens.
  • Keep authentication persistent: reuse a token or session, renew it once on 401, and log out.
  • Iterate over every page of a collection using the Link header or offset parameters.
  • Stay under a rate limit, and recover from 429 using Retry-After.
  • Turn each API’s error format into an exception that says what went wrong.

SECTION 1

Read the documentation first

CCIE topic 2.3 is “Consume and use a new API, given the documentation” (2.3.a REST; 2.3.b GraphQL, covered in TH-APP-003). In the lab you get a reference you have never seen, so read it in a fixed order. These are the answers your client needs before the first line of code:

QuestionWhere it is usually documentedMeraki Dashboard API v1Catalyst CenterSD-WAN Manager
Base URL and versionGetting startedhttps://api.meraki.com/api/v1https://<cluster>/dna/...https://<manager>/dataservice/...
How to authenticateAuthentication pageAPI key as Authorization: BearerBasic credentials → token → X-Auth-TokenSession cookie + XSRF token, or JWT (20.18.1 and later)
How long credentials lastAuthentication pageKey: until revokedNot stated on the guide page: handle 401Session 24 h, 30 min idle; JWT 30 min by default
How lists are pagedPagination pageLink header, perPage, startingAfter, endingBeforeCheck each endpointCheck each endpoint
Rate limitsRate limit page10 req/s per organization, 100 req/s per source IP, 429 + Retry-AfterCheck the release notesMax 100 concurrent sessions
Error formatErrors page{"errors": ["..."]}{"response": {...}}HTTP status + body; failed login returns HTML

The rest of the page goes through the table one column at a time. The numbers come from the Cisco documentation pages listed in References; check them again for the release you work with, because they change.

Diagram: One client, real APIs: authenticate once (Meraki bearer key, Catalyst Center X-Auth-Token, SD-WAN Manager JSESSIONID + X-XSRF-TOKEN), throttle with a token bucket and Retry-After on 429, follow Link rel="next" until there is none, and act on 401, 403, 429 and 5xx.

EXAM TIP

When a question gives you a piece of API documentation, the answer is in it: the header name, the parameter that carries the cursor, the status code for throttling. Read the documentation before you rely on what another API does.

SECTION 2

Authentication patterns

Static key as a bearer token (Meraki)

The Meraki Dashboard API v1 takes the API key in the standard Authorization header: a string that begins with Bearer followed by the key. The v0 header X-Cisco-Meraki-API-Key is the old form; the documentation tells you to use the bearer header instead. Admin API keys are permanent until revoked (each identity can hold up to two, which allows rotation), and the app-scoped OAuth 2.0 tokens last 60 minutes.

s = requests.Session()
s.headers["Authorization"] = f"Bearer {os.environ['MERAKI_API_KEY']}"

A 401 with a static key will not fix itself: there is nothing to renew. Report it and stop.

Token exchange (Catalyst Center)

The Catalyst Center Intent API uses a token endpoint. The client sends its user name and password once with HTTP Basic authentication to POST /dna/system/api/v1/auth/token. The JSON answer carries the token in the field Token, and every later request sends it in the X-Auth-Token header:

r = requests.post(f"{base}/dna/system/api/v1/auth/token", auth=(user, password), timeout=(5, 30))
r.raise_for_status()
s.headers["X-Auth-Token"] = r.json()["Token"]

The guide does not state the token lifetime on that page, so a robust client does not guess it: when a call returns 401, it gets a new token once and repeats the call (section 3).

Catalyst SD-WAN Manager supports session-based authentication, and since release 20.18.1 also JWT. The session flow has three steps:

  1. POST /j_security_check with the form fields j_username and j_password (application/x-www-form-urlencoded). On success the body is empty and the response sets the JSESSIONID cookie.
  2. GET /dataservice/client/token with that cookie. The body is the XSRF token.
  3. Later requests send the cookie; POST requests also send the token in the X-XSRF-TOKEN header.

TRAP

A failed SD-WAN Manager login does not have to come back as 401. The documented failure is a response whose body is the HTML login page. raise_for_status() sees nothing wrong; the next call then fails in a confusing way. Check the body for <html after the login, as the class in section 7 does.

Sessions are a limited resource. The documentation gives a lifespan of 24 hours, an inactivity timeout of 30 minutes and a maximum of 100 concurrent sessions, after which the oldest session is invalidated. A script that logs in on every run and never calls POST /logout uses up that pool, and can end up logging out a colleague’s session.

With JWT (20.18.1 and later), POST /jwt/login takes a JSON body with username, password and an optional duration in seconds. The answer carries the access token, a refresh token and the csrf value used as the XSRF token. Calls send Authorization: Bearer <token> (and X-XSRF-TOKEN on POST). The access token lasts 1,800 seconds by default; POST /jwt/refresh issues a new one. There is no logout endpoint for JWT.

OAuth 2.0 client credentials

Many cloud APIs (including Meraki’s app-scoped access) use OAuth 2.0. For a script that acts as itself, the grant is client credentials (RFC 6749, section 4.4): the client authenticates to the token endpoint and sends grant_type=client_credentials; the answer has access_token, token_type and, recommended, expires_in in seconds. A refresh token “SHOULD NOT be included” for this grant, so renewal simply means asking again. The token goes in Authorization: Bearer (RFC 6750). When it is expired or revoked, the resource server answers 401 with WWW-Authenticate: Bearer ... error="invalid_token".

PatternCredential on each callRenewalCisco example
Static keyAuthorization: Bearer <key>None: replace the keyMeraki Dashboard API v1
Token exchangeX-Auth-Token: <token>Ask for a new tokenCatalyst Center
Session + XSRFCookie: JSESSIONID=... + X-XSRF-TOKENLog in againSD-WAN Manager (session)
JWTAuthorization: Bearer <token> + X-XSRF-TOKENPOST /jwt/refreshSD-WAN Manager 20.18.1+
OAuth 2.0 client credentialsAuthorization: Bearer <token>New token request before expires_inCloud APIs, Meraki OAuth apps

SECTION 3

Persistent authentication

“Persistent authentication” in topic 1.6 means the script authenticates once and keeps that state for the whole run, instead of logging in before every call. Four rules make it work:

  • One session object for the run. A requests.Session keeps headers and, for cookie-based logins, the cookie jar: the requests documentation says a session “persists cookies across all requests made from the Session instance”.
  • Renew on 401, once. When the token expires mid-run, get a new one and repeat that one call. If the second attempt also fails, stop: repeating forever with bad credentials locks accounts. RFC 9110 says the same for 403: the client “SHOULD NOT automatically repeat the request with the same credentials”.
  • Renew before expiry when the lifetime is known. With expires_in (OAuth) or the JWT duration, refresh a little before the end, so long jobs do not hit a 401 in the middle of a change.
  • Release what you hold. Log out of session-based APIs in a finally block or a context manager.

TRAP

requests removes the Authorization header when a redirect leads to another host (“Authorization headers will be removed if you get redirected off-host”), which is why the Meraki documentation warns that tools strip it on redirects. Custom headers are a different story. Tested with requests 2.34.2, a redirect from 127.0.0.1 to localhost dropped Authorization but forwarded X-Auth-Token and X-Cisco-Meraki-API-Key to the new host. Only follow redirects to hosts you trust, and prefer the bearer header when the API accepts it.

SECTION 4

Pagination

An API that has 12,000 clients does not return them in one answer. It returns a page and tells you how to ask for the next one. There are three common styles:

StyleHow the next page is requestedRisk
Offset/limit?offset=200&limit=100Items added or removed while you page shift the window: duplicates or gaps
Cursor (token)?startingAfter=<value from the last page>None of the above, but the value must come from the API
Link headerFollow the URL in rel="next"The simplest: the server builds the next URL

The Meraki API combines the last two. It follows the Web Linking standard (RFC 8288): a paginated GET takes perPage, startingAfter and endingBefore, and the response carries a Link header with up to four links, first, prev, next and last. Which links appear depends on the endpoint. The startingAfter and endingBefore values are timestamps or IDs, depending on the operation, so do not compute them: follow the next URL until there is none.

requests parses the header for you into r.links:

r = s.get(f"{base}/organizations/{org}/devices", params={"perPage": 100}, timeout=(5, 30))
r.links.get("next", {}).get("url")   # the full URL of the next page, or None

The loop is a generator, so the caller can stop early and memory stays flat:

def paginate(self, path, params=None):
    url = path
    while url:
        resp = self.request("GET", url, params=params)
        yield from resp.json()
        url = resp.links.get("next", {}).get("url")
        params = None  # the next link already carries every query parameter

TRAP

Passing the original params again with the next URL duplicates the query parameters, because that URL already contains them. Send the link exactly as received.

SECTION 5

Rate limiting

A rate limit protects the platform from one client using all of it. The documented Meraki limits are a good model:

  • 10 requests per second per organization, shared by all applications that use API keys in that organization, with an extra 10 allowed in the first second (30 in two seconds). The documentation describes this as a token bucket.
  • 100 requests per second per source IP address.
  • Over the limit, the API returns 429 Too Many Requests with a Retry-After header telling you how long to wait.

429 and Retry-After are standard. RFC 6585 defines 429 as “the user has sent too many requests in a given amount of time” and says the response MAY include Retry-After. RFC 9110 defines two forms for that header: a number of seconds (Retry-After: 3) or an HTTP date. A client must accept both:

def retry_after_seconds(value, default):
    if not value:
        return default
    if value.strip().isdigit():
        return float(value)
    try:
        when = email.utils.parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return default
    return max(0.0, when.timestamp() - time.time())

Reacting to 429 is half the job. The other half is not causing it: a client-side limiter spaces the calls before they leave. Measured against the simulated API (server bucket: 2 requests per second, burst of 4), reading 7 pages:

no client limiter        -> 9 GETs (2 answered 429), 2.0 s
client limiter 2/s       -> 7 GETs, no 429, 3.0 s

Both runs got all the data. The first one spent two calls of the organization’s budget on refusals, and on Meraki that budget is shared with every other integration in the organization. Set your limiter below the documented limit when other applications use the same organization.

EXAM TIP

urllib3’s Retry (TH-PY-002) can retry 429 too, and it honours Retry-After, but only for the methods in allowed_methods, which leaves out POST and PATCH. A 429 means the server refused the request without serving it, which is why the client on this page waits and repeats it for any method. A 5xx is different: the request may have been executed, and only idempotent methods should be repeated.

SECTION 6

Error handling

Each platform has its own error body. A client that only calls raise_for_status() logs “400 Client Error” and loses the reason. Extract it:

PlatformError bodyExample
Meraki{"errors": [list of strings]}{"errors": ["VLANs are not enabled for this network"]}
RESTCONF (RFC 8040)ietf-restconf:errors → error list with error-tag, error-messageTH-PY-002, section 6
OAuth 2.0 token endpoint (RFC 6749){"error": "invalid_client"} (also invalid_grant, unsupported_grant_type, …)Wrong client secret
SD-WAN Manager loginHTML login pageWrong password

And decide per status class what the client does:

StatusMeaningClient action
400Bad request: often a missing or wrong parameterDo not repeat; fix the call. Log the body
401Not authenticated: no, expired or wrong credentialsRenew once (token, session); then stop
403Authenticated but not allowedDo not repeat with the same credentials
404Resource does not existDo not repeat; check the ID or the URL version
429Too many requestsWait Retry-After (or back off) and repeat
500, 502, 503, 504Server or gateway problemRepeat idempotent calls with backoff; Meraki notes that 502/504 may mean the request never reached the dashboard

SECTION 7

A client that puts it together

The module below is about 150 lines and covers sections 2 to 6: authentication strategies with renewal, one session for the run, a token-bucket limiter, 429 handling with both Retry-After forms, Link pagination and readable errors.

"""REST API client with pagination, token refresh, rate limiting and errors (TH-PY-003)."""

from __future__ import annotations

import email.utils
import logging
import threading
import time
from collections.abc import Iterator
from typing import Any

import requests

log = logging.getLogger(__name__)


class ApiError(Exception):
    """An API call failed; carries the status and the API's own error text."""

    def __init__(self, status: int, method: str, url: str, detail: str) -> None:
        self.status, self.method, self.url, self.detail = status, method, url, detail
        super().__init__(f"{method} {url} -> {status}: {detail}")


def error_detail(resp: requests.Response) -> str:
    """Extract the error text from the shapes Cisco APIs use."""
    try:
        body = resp.json()
    except ValueError:
        return resp.text[:200] or resp.reason
    if isinstance(body, dict):
        if isinstance(body.get("errors"), list):  # Meraki: list of strings
            return "; ".join(map(str, body["errors"]))
        rc = body.get("ietf-restconf:errors", {}).get("error")  # RFC 8040
        if rc:
            return rc[0].get("error-message") or rc[0].get("error-tag", "")
        if "error" in body:  # OAuth 2.0 (RFC 6749 5.2) and others
            return str(body["error"])
    return str(body)[:200]


def retry_after_seconds(value: str | None, default: float) -> float:
    """Retry-After is either delay-seconds or an HTTP-date (RFC 9110 10.2.3)."""
    if not value:
        return default
    if value.strip().isdigit():
        return float(value)
    try:
        when = email.utils.parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return default
    return max(0.0, when.timestamp() - time.time())


class RateLimiter:
    """Client-side token bucket: at most `rate` calls per second, bursts of `burst`."""

    def __init__(self, rate: float, burst: int) -> None:
        self.rate, self.burst = rate, float(burst)
        self.tokens, self.last = float(burst), time.monotonic()
        self.lock = threading.Lock()

    def acquire(self) -> None:
        with self.lock:
            while True:
                now = time.monotonic()
                self.tokens = min(self.burst, self.tokens + (now - self.last) * self.rate)
                self.last = now
                if self.tokens >= 1:
                    self.tokens -= 1
                    return
                time.sleep((1 - self.tokens) / self.rate)


class ApiKeyAuth:
    """Static key sent as a bearer token (Meraki Dashboard API v1)."""

    def __init__(self, key: str) -> None:
        self.key = key

    def apply(self, session: requests.Session) -> None:
        session.headers["Authorization"] = f"Bearer {self.key}"

    def refresh(self, session: requests.Session) -> bool:
        return False  # a 401 with a static key will not fix itself


class TokenAuth:
    """Token exchange: Basic credentials -> token -> X-Auth-Token (Catalyst Center)."""

    def __init__(self, token_url: str, username: str, password: str, verify: Any = True) -> None:
        self.token_url, self.creds, self.verify = token_url, (username, password), verify

    def apply(self, session: requests.Session) -> None:
        resp = requests.post(self.token_url, auth=self.creds, timeout=(5, 30), verify=self.verify)
        if resp.status_code != 200:
            raise ApiError(resp.status_code, "POST", self.token_url, error_detail(resp))
        session.headers["X-Auth-Token"] = resp.json()["Token"]
        log.info("new token obtained")

    def refresh(self, session: requests.Session) -> bool:
        self.apply(session)
        return True


class ApiClient:
    def __init__(
        self,
        base_url: str,
        auth: ApiKeyAuth | TokenAuth,
        rate: RateLimiter | None = None,
        timeout: tuple[float, float] = (5, 30),
        max_429: int = 5,
        verify: Any = True,
    ) -> None:
        self.base = base_url.rstrip("/")
        self.auth, self.rate, self.timeout = auth, rate, timeout
        self.max_429, self.verify = max_429, verify
        self.session = requests.Session()
        self.session.headers["Accept"] = "application/json"
        auth.apply(self.session)  # authenticate once, reuse for every call

    def request(self, method: str, path: str, **kwargs: Any) -> requests.Response:
        url = path if path.startswith("http") else f"{self.base}/{path.lstrip('/')}"
        refreshed, throttled = False, 0
        while True:
            if self.rate:
                self.rate.acquire()
            resp = self.session.request(
                method, url, timeout=self.timeout, verify=self.verify, **kwargs
            )
            if resp.status_code == 401 and not refreshed and self.auth.refresh(self.session):
                refreshed = True  # one new token, one more attempt
                continue
            if resp.status_code == 429 and throttled < self.max_429:
                wait = retry_after_seconds(resp.headers.get("Retry-After"), 2.0**throttled)
                throttled += 1
                log.warning("429 on %s %s, waiting %.1fs", method, url, wait)
                time.sleep(wait)
                continue
            if resp.status_code >= 400:
                raise ApiError(resp.status_code, method, url, error_detail(resp))
            return resp

    def paginate(self, path: str, params: dict[str, Any] | None = None) -> Iterator[Any]:
        """Follow rel="next" in the Link header (RFC 8288) until there is none."""
        url: str | None = path
        while url:
            resp = self.request("GET", url, params=params)
            yield from resp.json()
            url = resp.links.get("next", {}).get("url")
            params = None  # the next link already carries every query parameter

    def close(self) -> None:
        self.session.close()

Using it against the Meraki API looks like this (the organization ID comes from GET /organizations; check each endpoint’s reference for the accepted perPage range):

client = ApiClient(
    "https://api.meraki.com/api/v1",
    ApiKeyAuth(os.environ["MERAKI_API_KEY"]),
    rate=RateLimiter(5, 5),  # below 10/s: other integrations share the organization budget
)
for device in client.paginate(f"organizations/{org_id}/devices", {"perPage": 100}):
    print(device["serial"], device.get("name"))

Against the simulated API, the token-exchange client renewed its token once after the server expired it, and the call that got the 401 was repeated transparently:

INFO api_client: new token obtained
0 c9k-1 tok1
1 c9k-1 tok1
INFO api_client: new token obtained
2 c9k-1 tok2

With a wrong API key the client does not loop; the API’s own message reaches the log:

ApiError: GET http://127.0.0.1:8800/api/v1/organizations/1/devices -> 401: Invalid API key

SD-WAN Manager session as a context manager

"""Session-based login to Catalyst SD-WAN Manager with XSRF token and logout (TH-PY-003)."""

from __future__ import annotations

from typing import Any, Self

import requests


class SdwanSession:
    def __init__(self, base_url: str, username: str, password: str, verify: Any = True) -> None:
        self.base, self.verify = base_url.rstrip("/"), verify
        self.s = requests.Session()
        resp = self.s.post(
            f"{self.base}/j_security_check",
            data={"j_username": username, "j_password": password},  # form-encoded
            timeout=(5, 30),
            verify=verify,
        )
        # A failed login can still return 200: the body is the HTML login page.
        if resp.status_code != 200 or "<html" in resp.text.lower():
            raise PermissionError("SD-WAN Manager login failed")
        token = self.s.get(f"{self.base}/dataservice/client/token", timeout=(5, 30), verify=verify)
        token.raise_for_status()
        self.s.headers["X-XSRF-TOKEN"] = token.text  # needed on POST, harmless on GET

    def get(self, path: str) -> Any:
        resp = self.s.get(f"{self.base}/dataservice/{path}", timeout=(5, 30), verify=self.verify)
        resp.raise_for_status()
        return resp.json()

    def post(self, path: str, body: dict) -> Any:
        resp = self.s.post(
            f"{self.base}/dataservice/{path}", json=body, timeout=(5, 30), verify=self.verify
        )
        resp.raise_for_status()
        return resp.json()

    def logout(self) -> None:
        self.s.post(
            f"{self.base}/logout", params={"nocache": "1"}, timeout=(5, 30), verify=self.verify
        )
        self.s.close()

    def __enter__(self) -> Self:
        return self

    def __exit__(self, *exc: object) -> None:
        self.logout()  # free the session even when the script fails

The with block guarantees the logout even when the code inside fails, so the run returns its session to the pool of 100:

with SdwanSession("https://manager.lab", user, password, verify="ca.pem") as sd:
    devices = sd.get("device")

OAuth 2.0 client credentials as a requests auth hook

requests lets you plug authentication into every request by subclassing AuthBase and implementing __call__. The hook below gets a token, reuses it, and renews it 60 seconds before expires_in runs out:

"""OAuth 2.0 client credentials with proactive renewal (RFC 6749 4.4) (TH-PY-003)."""

from __future__ import annotations

import time

import requests


class ClientCredentials(requests.auth.AuthBase):
    """requests auth hook: fetch a token, reuse it, renew it before it expires."""

    def __init__(
        self, token_url: str, client_id: str, client_secret: str, margin: int = 60
    ) -> None:
        self.token_url, self.client = token_url, (client_id, client_secret)
        self.margin, self.token, self.expires = margin, "", 0.0

    def _fetch(self) -> None:
        resp = requests.post(
            self.token_url,
            data={"grant_type": "client_credentials"},
            auth=self.client,  # client authentication with HTTP Basic (RFC 6749 2.3.1)
            timeout=(5, 30),
        )
        resp.raise_for_status()
        body = resp.json()
        self.token = body["access_token"]
        self.expires = time.monotonic() + int(body.get("expires_in", 300))

    def __call__(self, req: requests.PreparedRequest) -> requests.PreparedRequest:
        if not self.token or time.monotonic() > self.expires - self.margin:
            self._fetch()
        req.headers["Authorization"] = f"Bearer {self.token}"
        return req

    def invalidate(self) -> None:
        self.token = ""  # call after a 401 with error="invalid_token" (RFC 6750 3.1)
auth = ClientCredentials(token_url, client_id, client_secret)
r = requests.get(url, auth=auth, timeout=(5, 30))
if r.status_code == 401 and 'error="invalid_token"' in r.headers.get("WWW-Authenticate", ""):
    auth.invalidate()
    r = requests.get(url, auth=auth, timeout=(5, 30))

What the exam expects

  • ✓ Read an unfamiliar API reference and find the base URL, authentication method, pagination scheme, rate limits and error format.
  • ✓ Authenticate with a static key, a token exchange, a session with XSRF token, and OAuth 2.0 client credentials or JWT; send the credential in the header the API documents.
  • ✓ Keep authentication persistent: reuse the session or token, renew once on 401, refresh before expiry when the lifetime is known, and log out.
  • ✓ Iterate over all pages using Link headers (rel="next") or cursor/offset parameters without duplicates.
  • ✓ Respect rate limits with a client-side limiter and recover from 429 using Retry-After in both forms.
  • ✓ Map status codes to actions and surface each API’s error body.

EXAM CHECK · 350-901 TOPIC 1.6

Read it like the exam

1. A script lists 3,000 Meraki devices with perPage=1000 but only ever gets the first 1,000. The code reads r.json() once. What is missing?

Pagination. The Meraki API returns one page per request and a Link header; the script must follow rel="next" (in requests, r.links["next"]["url"]) until the header no longer has a next link.

2. A job calls the Catalyst Center Intent API for two hours. After a while every call returns 401, although the password is correct. What should the client do?

Treat it as an expired token: request a new one from POST /dna/system/api/v1/auth/token with Basic authentication, update X-Auth-Token, and repeat the failed call once. If the repeated call also fails, stop and report it instead of retrying forever.

3. Three integrations in the same Meraki organization each run at 8 requests per second and start receiving 429. Each one alone stays under 10 per second. Why?

The limit is 10 requests per second per organization, shared by all applications that use API keys in that organization. Together they send 24 per second. Each client must honour Retry-After, and their client-side limiters must be set so that the sum stays under the organization limit.

4. An SD-WAN Manager login returns 200, but the next GET /dataservice/device fails. The body of the login response starts with <html>. What happened, and what is the risk of logging in again on every call?

The login failed: SD-WAN Manager returns the HTML login page instead of setting JSESSIONID, so checking only the status code misses it. Logging in on every call creates many sessions; with a maximum of 100 concurrent sessions, the oldest are invalidated, which can disconnect other users. Log in once, reuse the session and call POST /logout at the end.

5. An API answers 429 with Retry-After: Wed, 25 Nov 2026 14:30:00 GMT. The client does time.sleep(int(r.headers["Retry-After"])). What happens, and how do you fix it?

int() raises ValueError: RFC 9110 allows Retry-After to be either a number of seconds or an HTTP date. Parse both forms (for example email.utils.parsedate_to_datetime for the date) and fall back to exponential backoff when the header is missing or invalid.

All 15 pages of Python, NETCONF & RESTCONF
  1. TH-PY-001Python for network automation: environment, data structures and good practice
  2. TH-PY-002HTTP clients in Python for RESTCONF: requests and httpx
  3. TH-PY-003Consuming real REST APIs: pagination, authentication, rate limiting and errorsYou are here
  4. TH-PY-004NETCONF with ncclient: sessions, edit-config and filters in scripts
  5. TH-PY-005Netmiko and Scrapli: automated CLI with structured output
  6. TH-PY-006Nornir: inventory, tasks and parallel execution
  7. TH-PY-007Python on IOS XE: VLANs, OSPF, interfaces, ACLs and asset inventory
  8. TH-PY-008Netmiko, Scrapli or Nornir: how to choose
  9. TH-REST-001YANG for network engineers: reading a data model
  10. TH-REST-002From YANG to data: JSON, XML and YAML instances
  11. TH-REST-003RESTCONF on IOS XE: resources, URIs and methods
  12. TH-REST-004RESTCONF in practice: interfaces, VLANs, OSPF, ACLs and inventory
  13. TH-REST-005NETCONF on IOS XE: operations, datastores and XPath filters
  14. TH-REST-006YANG tooling and troubleshooting on IOS XE
  15. TH-REST-007RESTCONF and NETCONF in practice: static routes, BGP and routing tables

PRACTICE

Labs in this path

  1. LAB-PY-001Your first RESTCONF call to a Cisco routerFreeOpen the free lab
  2. LAB-PY-002Discover the YANG models of your Cisco routerPremiumOpen the lab