# FRED API in Python: get a key, pull a series, handle rate limits

The FRED API lives at `https://api.stlouisfed.org/fred` and every request needs a free 32-character API key from your fredaccount.stlouisfed.org account. To get data, send a GET to `/fred/series/observations` with `series_id`, `api_key` and `file_type=json`. The documented rate limit is 120 requests per minute; past that you get HTTP 429, and the [FRED error docs](https://fred.stlouisfed.org/docs/api/fred/errors.html) warn that ignoring the throttle can get you temporarily blocked.

This guide covers version 1 of the API, which serves single series, search, categories and releases. The facts below were read from the [FRED API documentation](https://fred.stlouisfed.org/docs/api/fred/) on 2026-11-12.

## How to get a FRED API key

You get a FRED API key by logging into a free account at fredaccount.stlouisfed.org and requesting one from the [API Keys page](https://fred.stlouisfed.org/docs/api/api_key.html). The docs and terms of use list no fee for it. It is a 32-character string of lower-case letters and digits, and you pass it as the `api_key` query parameter on every call.

The docs set three rules. Request a separate key for each application you build. Every user of an application should use their own key. And the example key in the docs, `abcdefghijklmnopqrstuvwxyz123456`, is for show only: send it and FRED answers with a 400 that says the key is not registered.

Keep the key out of your code. Put it in an environment variable and read it at run time:

```bash
export FRED_API_KEY=YOUR_API_KEY
```

On Windows PowerShell, use `$env:FRED_API_KEY = "YOUR_API_KEY"`. The `fredapi` package reads the same variable name, so one setting serves both examples below.

## How to pull a FRED series in Python

You pull a series with one GET to `series/observations`, passing the series ID and `file_type=json`, because the default response format is XML. The helper below adds the key, waits half a second between calls to stay under 120 a minute, retries on 429 and 500, and raises FRED's own error message on anything else.

```python
import os
import time

import requests

API_KEY = os.environ["FRED_API_KEY"]  # set to YOUR_API_KEY
BASE_URL = "https://api.stlouisfed.org/fred"
MIN_INTERVAL = 0.5  # seconds between calls: 120 per minute at most

_last_call = 0.0


def fred_get(path, **params):
    """Call a FRED v1 endpoint and return the parsed JSON body."""
    global _last_call
    params.update(api_key=API_KEY, file_type="json")
    for attempt in range(5):
        wait = MIN_INTERVAL - (time.monotonic() - _last_call)
        if wait > 0:
            time.sleep(wait)
        _last_call = time.monotonic()
        resp = requests.get(f"{BASE_URL}/{path}", params=params, timeout=30)
        if resp.status_code == 200:
            return resp.json()
        if resp.status_code in (429, 500):
            retry_after = resp.headers.get("Retry-After", "")
            time.sleep(int(retry_after) if retry_after.isdigit() else 10 * 2 ** attempt)
            continue
        try:
            message = resp.json().get("error_message", resp.text)
        except ValueError:
            message = resp.text
        raise RuntimeError(f"FRED {resp.status_code}: {message}")
    raise RuntimeError(f"FRED still failing after retries: {path}")


def observations(series_id, start=None, end=None, **extra):
    """Return a list of (date, value) pairs; FRED's '.' becomes None."""
    params = {"series_id": series_id, **extra}
    if start:
        params["observation_start"] = start
    if end:
        params["observation_end"] = end
    body = fred_get("series/observations", **params)
    return [
        (row["date"], None if row["value"] == "." else float(row["value"]))
        for row in body["observations"]
    ]


if __name__ == "__main__":
    for date, value in observations("UNRATE", start="2024-01-01")[-6:]:
        print(date, value)
```

Each observation comes back with `date`, `value`, `realtime_start` and `realtime_end`, and in the JSON the value is a string. FRED writes a missing value as a single dot (`"."`), so convert it before you do arithmetic. One call returns up to 100,000 observations; use `limit` and `offset` if you need to page.

The [series/observations docs](https://fred.stlouisfed.org/docs/api/fred/series_observations.html) list the options that save you work after the download. `units=pc1` returns percent change from a year ago and `units=log` the natural log. `frequency=q` with `aggregation_method=avg`, `sum` or `eop` turns a monthly series into a quarterly one on FRED's side. If you ask for a frequency higher than the series' native one, such as daily for a monthly series, FRED returns an error.

To get a pandas DataFrame from the same call:

```python
import pandas as pd

rows = fred_get("series/observations", series_id="CPIAUCSL")["observations"]
df = pd.DataFrame(rows)
df["date"] = pd.to_datetime(df["date"])
df["value"] = pd.to_numeric(df["value"], errors="coerce")  # "." becomes NaN
cpi = df.set_index("date")["value"]
print(cpi.tail())
```

## FRED API rate limit

The FRED API rate limit is 120 requests per minute. The [errors page](https://fred.stlouisfed.org/docs/api/fred/errors.html) says that is how many you can send "before being served a 429 error code", that not following the throttle can lead to a temporary block, and that you should contact FRED if you have a real need to go higher. The docs do not say how long a block lasts or whether a 429 carries a `Retry-After` header, so the helper above reads the header if it is there and otherwise backs off for 10, 20, 40 seconds and so on.

Three habits keep you well under the limit:

- **Space your calls.** One call every half second is exactly 120 a minute. If several processes share one key, give each a smaller share.
- **Ask for whole histories.** One `series/observations` call can return 100,000 rows, so you rarely need a call per year or per date.
- **Cache results.** Monthly and quarterly series change only when a new release comes out. Save each response and fetch again only after the release date, which `fred/release/dates` gives you.

If you need every series on a release, such as all of the Z.1 Financial Accounts, look at [API version 2](https://fred.stlouisfed.org/docs/api/fred/v2/index.html). Its one endpoint, `fred/v2/release/observations`, returns the observations for every series on a release and pages with `next_cursor`. Version 2 takes the key in a header, `Authorization: Bearer YOUR_API_KEY`, instead of a query parameter.

## Main FRED API endpoints

The main FRED endpoints are the series calls, which return metadata and data for one series, and the category and release calls, which help you find series. All the version 1 endpoints take `api_key` and `file_type`, and the ones with lists accept `limit` and `offset`.

| Endpoint | What it returns | Key parameters |
|---|---|---|
| `fred/series` | Metadata for one series: title, units, frequency, seasonal adjustment, last update | `series_id` |
| `fred/series/observations` | The data points for one series | `series_id`, `observation_start`, `observation_end`, `units`, `frequency`, `aggregation_method`, `output_type`, `vintage_dates`, `limit` (up to 100,000) |
| `fred/series/search` | Series that match keywords | `search_text`, `search_type` (`full_text` or `series_id`), `order_by` (e.g. `popularity`), `filter_variable`, `tag_names`, `limit` (up to 1,000) |
| `fred/series/vintagedates` | The dates a series was revised or had new values released | `series_id`, `limit` (up to 10,000) |
| `fred/category` | One category; `category_id=0` is the root | `category_id` |
| `fred/category/children` | The subcategories of a category | `category_id` |
| `fred/category/series` | The series in a category | `category_id`, `order_by`, `filter_variable`, `tag_names`, `limit` (up to 1,000) |
| `fred/releases` | All releases of economic data | `order_by`, `limit` (up to 1,000) |
| `fred/release` | One release, such as Gross Domestic Product | `release_id` |
| `fred/release/series` | The series on one release | `release_id`, `order_by`, `filter_variable`, `limit` (up to 1,000) |
| `fred/release/dates` | Release dates for one release | `release_id`, `include_release_dates_with_no_data`, `limit` (up to 10,000) |
| `fred/v2/release/observations` | Observations for every series on a release (API v2) | `release_id`, `format` (default `json`), `limit` (up to 500,000), `next_cursor`; key in a Bearer header |

The full list, including sources and tags, is on the [FRED API index](https://fred.stlouisfed.org/docs/api/fred/).

## Revised vs. original values (ALFRED, realtime_start and realtime_end)

You get past versions of a series by setting `realtime_start` and `realtime_end` on `series/observations`, which switches FRED into ALFRED mode and returns values as they were known during that period. By default both parameters are today's date, so you see only the latest revised numbers. The [real-time periods page](https://fred.stlouisfed.org/docs/api/fred/realtime_period.html) explains that the period includes both end dates, and that `1776-07-04` and `9999-12-31` are the earliest and latest bounds.

Three requests cover most needs:

```python
# Every vintage of quarterly GDP: one row per value per real-time period.
all_vintages = fred_get(
    "series/observations",
    series_id="GDP",
    realtime_start="1776-07-04",
    realtime_end="9999-12-31",
)["observations"]

# Only the first published value for each quarter (output_type=4).
first_release = fred_get(
    "series/observations", series_id="GDP", output_type=4
)["observations"]

# The data as it stood on chosen dates in history.
as_of = fred_get(
    "series/observations", series_id="GDP", vintage_dates="2020-07-30,2021-07-29"
)["observations"]

# The dates on which GDP was revised or had new values released.
revision_dates = fred_get("series/vintagedates", series_id="GDP")["vintage_dates"]
```

`output_type` sets the shape of the answer: 1 gives observations by real-time period (the default), 2 by vintage date with all observations, 3 by vintage date with only new and revised values, and 4 the initial release only. The docs cap `vintage_dates` at 2,000 dates per JSON or XML request for most series. Use first-release data when you are testing a model or a trading rule, because the latest values contain revisions nobody had at the time.

## How to search for a FRED series ID

You find a series ID by calling `fred/series/search` with `search_text`, or by searching fred.stlouisfed.org, where the ID is the last part of each series URL (`fred.stlouisfed.org/series/UNRATE`). Sorting by popularity puts the series most people use first, which helps when a search returns hundreds of close variants.

```python
hits = fred_get(
    "series/search",
    search_text="unemployment rate",
    order_by="popularity",
    limit=5,
)["seriess"]
for s in hits:
    print(s["id"], s["frequency_short"], s["seasonal_adjustment_short"], s["title"])
```

The list key really is `seriess` with two s's. To narrow the results, add `filter_variable="frequency"` with `filter_value="Monthly"`, or `tag_names` with a semicolon-separated list of tags the series must all have. To browse instead of search, start at `fred/category` with `category_id=0` and walk down with `fred/category/children`. A few IDs worth knowing: `GDP` (gross domestic product), `UNRATE` (unemployment rate) and `CPIAUCSL` (consumer price index for all urban consumers).

## fredapi vs plain requests

Use `fredapi` if you want pandas Series back in one line and work mostly with single series; use plain `requests` if you need rate-limit handling, retries, JSON, or endpoints the package does not wrap. [fredapi](https://github.com/mortada/fredapi) is a small open-source wrapper, version 0.5.2 on [PyPI](https://pypi.org/project/fredapi/), that depends on pandas.

```python
import os

from fredapi import Fred

fred = Fred(api_key=os.environ["FRED_API_KEY"])  # Fred() alone also reads FRED_API_KEY

unrate = fred.get_series("UNRATE", observation_start="2020-01-01")  # pandas Series
info = fred.get_series_info("UNRATE")                              # metadata
gdp_first = fred.get_series_first_release("GDP")                   # initial releases
gdp_all = fred.get_series_all_releases("GDP")                      # every vintage
gdp_then = fred.get_series_as_of_date("GDP", "2020-07-30")         # known on that date
matches = fred.search("unemployment rate", order_by="popularity", limit=5)
print(unrate.tail())
```

The trade-offs, read from the package source on 2026-11-12:

- **Good:** `get_series` returns a pandas Series indexed by date and turns `"."` into NaN for you. The ALFRED helpers save you from writing the vintage logic yourself.
- **Missing:** it has no throttle or retry code. A loop over many series can hit the 120-a-minute limit, and a 429 surfaces as an exception rather than a pause. Add your own `time.sleep(0.5)` between calls.
- **Errors:** it calls FRED with Python's `urllib`, and a FRED error response is raised as a `ValueError` carrying FRED's message, so catch `ValueError`, not `requests` exceptions.
- **Coverage:** it wraps series data and metadata, vintages, search, and the series lists for a release or a category. For release dates, tags, sources or API v2, call the endpoint directly with the helper above.

## Common FRED API errors and fixes

Most errors you will hit are a 400 with a message that names the problem, so print `error_message` before you change anything. The messages below were returned by the live API on 2026-11-12, except where the table says otherwise.

| Status and message | Cause | Fix |
|---|---|---|
| 400 "Variable api_key is not set." | No `api_key` parameter | Add `api_key`; check the environment variable is set in the shell that runs your code |
| 400 "The value for variable api_key is not registered." | The key is mistyped, not yours, or the demo key | Copy the key again from your fredaccount.stlouisfed.org account |
| 400 "...is not a 32 character alpha-numeric lower-case string." | Typo, extra space or quotes around the key | Strip whitespace and quotes; the key is lower case |
| 400 "The series does not exist." | Wrong or misspelled `series_id` | Look the ID up with `series/search` or on the series page (message as quoted by fredapi's tests) |
| Error on a `frequency` value | Asked for a frequency higher than the series' own | Request the native frequency or a lower one |
| 404 "Not Found" | Wrong endpoint path, such as `serie/observations` | Check the path against the endpoint table |
| 429 Too Many Requests | More than 120 requests in a minute | Space calls 0.5 seconds apart, back off, cache |
| 500 Internal Server Error | A problem on FRED's side | Retry with backoff |
| Value is `"."` | No observation for that date | Treat it as missing: `None` or NaN |

The docs also list 423 Locked without saying when it occurs. If you see it, stop and retry later rather than looping.

## Reusing FRED data in a product

You can use the API in your own applications, but some series belong to third parties and need the owner's permission for anything beyond personal use. The [FRED API terms of use](https://fred.stlouisfed.org/docs/api/terms_of_use.html) say copyrighted series carry the word "Copyright" in their notes, and that FRED blocks requests with an invalid key. Check the notes from `fred/series` before you publish or resell a series.

## When you need FRED next to other sources

Hyperresearch's [Answers API](/answers) already queries FRED alongside 120+ other public data sources and returns cited answers.

## Sources

- FRED API, Version 1 index: https://fred.stlouisfed.org/docs/api/fred/
- API Keys: https://fred.stlouisfed.org/docs/api/api_key.html
- Errors and rate limit: https://fred.stlouisfed.org/docs/api/fred/errors.html
- fred/series/observations: https://fred.stlouisfed.org/docs/api/fred/series_observations.html
- fred/series: https://fred.stlouisfed.org/docs/api/fred/series.html
- fred/series/search: https://fred.stlouisfed.org/docs/api/fred/series_search.html
- fred/series/vintagedates: https://fred.stlouisfed.org/docs/api/fred/series_vintagedates.html
- Real-time periods: https://fred.stlouisfed.org/docs/api/fred/realtime_period.html
- fred/category: https://fred.stlouisfed.org/docs/api/fred/category.html
- fred/category/series: https://fred.stlouisfed.org/docs/api/fred/category_series.html
- fred/releases: https://fred.stlouisfed.org/docs/api/fred/releases.html
- fred/release: https://fred.stlouisfed.org/docs/api/fred/release.html
- fred/release/series: https://fred.stlouisfed.org/docs/api/fred/release_series.html
- fred/release/dates: https://fred.stlouisfed.org/docs/api/fred/release_dates.html
- FRED API, Version 2: https://fred.stlouisfed.org/docs/api/fred/v2/index.html
- fred/v2/release/observations: https://fred.stlouisfed.org/docs/api/fred/v2/release_observations.html
- FRED API Terms of Use: https://fred.stlouisfed.org/docs/api/terms_of_use.html
- fredapi on GitHub: https://github.com/mortada/fredapi
- fredapi on PyPI: https://pypi.org/project/fredapi/
