# The API said 202 Accepted. The report still isn't there

> A 202 only promises the work will be processed; how long to wait, and when to give up, is left entirely to the client.

Original: https://fdetimes.net/en/guides/async-polling-202-accepted-python-httpx/

Microsoft's C# sample for the Power BI exportToFile API contains a very short note about the Retry-After header: it holds the time to wait before the next poll, but it does not always have a value.

That note says more about integration work than any architecture slide. Even a major report export API such as exportToFile runs asynchronously and makes the client poll, so your client has to behave correctly even when the server does not send everything it should.

FDEs run into this constantly. A client wants its revenue report pulled into a pipeline every night, or wants an agent to export PDFs for the operations team. The API call itself takes five lines of code. The hard part is the waiting: how often to ask, when to stop, and how to avoid accidentally creating ten identical export jobs on the client's system.

This guide builds a Python client with httpx that does four things. It creates the export exactly once, polls according to Retry-After, falls back to backoff with jitter, and stops on its own when a deadline passes. The API in the examples is hypothetical, to keep things readable. The `/exports` endpoint, the `status` field and the `succeeded`/`failed` values will differ from client to client.

## What you need before you start

You need Python 3.10 or later, the `httpx` library installed with `pip install httpx`, and an API that behaves as follows. `POST /exports` returns `202 Accepted` with a `Location` header pointing to a status resource. A `GET` to that address returns the job's status. When the job finishes, the server either returns the result in the body or redirects to a file.

One point to keep in mind before writing a single line. RFC 9110 defines 202 as meaning the request has been accepted for processing, but the processing has not been completed. So a 202 does not promise the report is ready, nor that the job will succeed.

## Step 1: build the client with timeouts and connection retries

```python
import random, time, uuid
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import httpx

client = httpx.Client(
    base_url="https://api.customer.example",  # hypothetical
    transport=httpx.HTTPTransport(retries=3),
    timeout=httpx.Timeout(10.0),
    headers={"Authorization": "Bearer <token>"},
)
```

By default, httpx raises a `TimeoutException` after 5 seconds of network inactivity. Here it is raised to 10 seconds because client endpoints are often slow. The number is your choice; tune it to the real system.

Do not misread `retries=3`. The httpx documentation states plainly that the transport retries only on `httpx.ConnectError` or `httpx.ConnectTimeout`. A 503 response will not be retried, and the documentation points to tools such as tenacity for that case. Check: disconnect from the network and make a call. You should see a `ConnectError` after a few attempts, not an endless loop.

## Step 2: create the export exactly once

The POST that creates the export is not idempotent. RFC 9110 advises that a client should not automatically retry such a request unless it knows the semantics are in fact idempotent or can detect that the original request was never applied.

Retrying connection errors in step 1 fits the second condition, because if the connection never opened, the request cannot have reached the server. A timeout midway through is different: you do not know whether the server created the job.

The way out is an idempotency key. According to Microsoft's description of the Asynchronous Request-Reply pattern, an API can require the client to send a key with the first request. On receiving a duplicate key, the back end returns the existing status resource instead of queuing a second job. The header name and the status code for a duplicate key used here are assumptions; read the client's API documentation.

```python
def create_export(params: dict, key: str) -> str:
    r = client.post("/exports", json=params,
                    headers={"Idempotency-Key": key})
    # 202: new job; 200: duplicate key, existing job returned (assumed)
    if r.status_code in (200, 202) and "Location" in r.headers:
        return r.headers["Location"]
    r.raise_for_status()
    raise RuntimeError(f"Expected 202 or 200, got {r.status_code}")

key = str(uuid.uuid4())  # store this key with the job record
```

The function accepts both 200 and 202. If it accepted only 202, a repeat call with the old key could get back the very job already running and still throw, and you would lose the whole benefit of the idempotency key.

Check: call `create_export` twice with the same `key`. If the API supports keys, both calls must return the same `Location`. If you get two different addresses, the API does not support them, and you must not automatically resend the POST on a timeout.

## Step 3: parse Retry-After in both forms

RFC 9110 allows Retry-After to be either an HTTP-date or a number of seconds. Write `int(value)` because you are used to the seconds form, and the function will die on precisely the day the client's gateway sends a date.

```python
def parse_retry_after(value: str | None) -> float | None:
    if not value:
        return None
    v = value.strip()
    if v.isdigit():
        return float(v)
    try:
        when = parsedate_to_datetime(v)
    except (TypeError, ValueError):
        return None
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
```

The function returns `None` when the header is missing or malformed. That is the case the Power BI sample warns about, and the loop in step 4 will fall back to its own wait time.

## Step 4: poll with backoff, jitter and a deadline

In Microsoft's pattern, every successful call to the status endpoint returns 200 OK, even while the job is still running. A client's API may behave differently, for instance returning 202 for as long as the job runs, so the code below does not rely on the status code to tell when the job is done. It reads the body.

RFC 6585 adds another case: a 429 Too Many Requests response may include Retry-After to say how long to wait before calling again.

```python
def wait_for_export(status_url: str, deadline_s=900, base=2.0,
                    cap=60.0, min_wait=1.0):
    expires_at = time.monotonic() + deadline_s
    attempt = 0
    while True:
        r = client.get(status_url)
        if r.status_code == 303:
            return r.headers["Location"]          # step 5
        if r.status_code in (429, 503):
            wait = parse_retry_after(r.headers.get("Retry-After"))
        else:
            r.raise_for_status()
            body = r.json()
            if body.get("status") == "succeeded":
                return body["result_url"]          # hypothetical
            if body.get("status") == "failed":
                raise RuntimeError(f"Export failed: {body}")
            wait = parse_retry_after(r.headers.get("Retry-After"))
        if wait is None:
            wait = random.uniform(0, min(cap, base * 2 ** attempt))
        wait = max(wait, min_wait)                 # no rapid-fire polling
        attempt += 1
        if time.monotonic() + wait > expires_at:
            raise TimeoutError("Export deadline exceeded")
        time.sleep(wait)
```

The code rests on three choices. The server's Retry-After always takes priority, because the server knows its own load better than you do. The fallback wait grows exponentially up to a cap, and is then picked at random between zero and that value.

The Amazon Builders' Library calls this randomness jitter: it spreads retries out over time so that hundreds of clients do not knock on the door at once.

The third choice is `expires_at`. The httpx documentation defines the read timeout as the maximum time to wait for a chunk of data. It does not cap the total duration of a request, let alone the whole polling loop. Without a separate deadline, a job stuck on the client's side will hold your worker forever.

**Key point:** Timeouts protect each call; only a deadline protects the whole job.

One small detail remains: the `min_wait` floor. A Retry-After of `0`, an HTTP-date already in the past, or a jitter draw close to zero all produce a wait of almost nothing. Without the floor, the loop would hammer the client's endpoint with requests.

Check: stand up a fake endpoint that returns `{"status": "running"}` forever and set `deadline_s=30`. The function must raise `TimeoutError` before the 30-second mark, the logged waits should show visible randomness, and none should be under 1 second.

## Step 5: fetch the file, even when redirected

If the status endpoint redirects when the job is done, Microsoft recommends 303 See Other. That code tells the client to send a GET to the new URL, whatever method the original request used. httpx does not follow redirects by default, and `raise_for_status()` raises on any non-2xx response, including an unfollowed 303. That is why step 4 catches the 303 before calling `raise_for_status()`.

```python
def download_result(url: str, path: str) -> None:
    r = client.get(url)
    r.raise_for_status()
    with open(path, "wb") as f:
        f.write(r.content)  # simplified: reads the whole file into RAM

loc = create_export({"report": "monthly-revenue"}, key)
download_result(wait_for_export(loc), "revenue.pdf")
```

For large files, stream the download instead of reading all of `r.content` into memory. The version above is kept short for readability.

## The mistakes that break this client in production

The most common mistake is treating 202 as done and reading the file straight away. The second is wrapping the whole `create_export` function in a generic retry decorator, so that every timeout spawns another heavy job on the client's data warehouse. The third is believing `HTTPTransport(retries=...)` takes care of everything, when 503 and 429 pass straight through.

Two more are harder to spot. One is checking only the status code while polling, when in Microsoft's pattern the status endpoint returns 200 the whole time the job runs and the real state lives in the body. The other is parsing Retry-After with `int()`, which works fine while the server sends seconds and then crashes the first time it receives an HTTP-date.

## On site, call it by hand before writing code

At the client's site, the first thing to do is make one call by hand and record everything: the POST's status code, the `Location` header, every polling response, and whether Retry-After is present and in which form.

Those ten minutes of notes give you enough to set `base`, `cap`, `min_wait` and `deadline_s` from real data instead of guesses. Then ask the client's team one question: does the API accept an idempotency key, and if not, what harm does a duplicate job do?

In interviews or on a CV, do not write "integrated REST APIs". Say specifically that you wrote a client for an asynchronous export API with an idempotency key, one that respects Retry-After and enforces an overall deadline. An FDE interviewer will know at once that you have lived with the consequences of someone else's slow system.

The next time someone tells you "the API returns 202, so we're fine", ask them: and then how long does the client wait?

**Try this week:**

- Take a real export API from a client or a sandbox (Power BI exportToFile, for example) and record the exact status code and Retry-After header of every poll.
- Write unit tests for parse_retry_after with three inputs: '120', an HTTP-date and an empty string.
- Review your existing integration code for any place that retries a POST without an idempotency key.

## Sources

- [RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110.html)

- [RFC 6585: Additional HTTP Status Codes](https://www.rfc-editor.org/rfc/rfc6585.html)

- [Asynchronous Request-Reply Pattern - Azure Architecture Center | Microsoft Learn](https://learn.microsoft.com/en-us/azure/architecture/patterns/asynchronous-request-reply)

- [Timeouts - HTTPX](https://www.python-httpx.org/advanced/timeouts/)

- [Transports - HTTPX](https://www.python-httpx.org/advanced/transports/)

- [QuickStart - HTTPX](https://www.python-httpx.org/quickstart/)

- [Timeouts, retries, and backoff with jitter](https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter)

- [Export Power BI embedded analytics reports API - Power BI | Microsoft Learn](https://learn.microsoft.com/en-us/power-bi/developer/embedded/export-to)
