AttributeError: 'State' object has no attribute 'redis'
app.state is a plain namespace object. Reading an attribute that was never assigned raises this error, so the real question is why the code that assigns it did not run, or ran on a different object.
Traceback (most recent call last):
File "/app/.venv/lib/python3.12/site-packages/starlette/middleware/errors.py", line 165, in __call__
await self.app(scope, receive, _send)
File "/app/.venv/lib/python3.12/site-packages/starlette/routing.py", line 73, in app
response = await f(request)
File "/app/.venv/lib/python3.12/site-packages/fastapi/routing.py", line 301, in app
raw_response = await run_endpoint_function(
File "/app/.venv/lib/python3.12/site-packages/fastapi/routing.py", line 212, in run_endpoint_function
return await dependant.call(**values)
File "/app/app/routes/items.py", line 14, in read_item
value = await request.app.state.redis.get(f"item:{item_id}")
File "/app/.venv/lib/python3.12/site-packages/starlette/datastructures.py", line 702, in __getattr__
raise AttributeError(message.format(self.__class__.__name__, key))
AttributeError: 'State' object has no attribute 'redis'
TLDR
- Fails only in tests:
TestClient(app)was not used withwith, so the lifespan never ran. Usewith TestClient(app) as client:. - Fails everywhere, and the app uses
@app.on_event("startup")pluslifespan=: theon_eventhandlers are skipped. Move the setup into the lifespan function. - Fails with
request.state: values yielded from lifespan as a dict are read fromrequest.state, notapp.state. - Fails only with multiple apps (mounted sub-app or a separate
FastAPI()instance): the attribute was set on a different app object.
with TestClient(app) as client:
client.get("/items/1")
TestClient without a with block
This is the most common cause. The lifespan function runs when the client enters its context, not when it is constructed.
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
import redis.asyncio as redis
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.redis = redis.from_url("redis://localhost:6379")
yield
await app.state.redis.aclose()
app = FastAPI(lifespan=lifespan)
@app.get("/items/{item_id}")
async def read_item(item_id: int, request: Request):
return {"value": await request.app.state.redis.get(f"item:{item_id}")}
client = TestClient(app) # lifespan has not run
client.get("/items/1") # AttributeError: 'State' object has no attribute 'redis'
The fix is the context manager form, usually inside a fixture:
import pytest
from fastapi.testclient import TestClient
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
If you test with httpx.AsyncClient(transport=ASGITransport(app=app)), the lifespan is also not run. Wrap the app with LifespanManager from the asgi-lifespan package, or assign the attributes yourself in the fixture (app.state.redis = FakeRedis()), which is often what you want in a test anyway. For event loop problems in async fixtures, see FastAPI pytest async event loop troubleshooting.
on_event handlers are ignored when lifespan is set
If the app was written with @app.on_event("startup") and someone later added lifespan=, only the lifespan function runs. The old handlers are silently skipped, so whatever they assigned to app.state is missing.
app = FastAPI(lifespan=lifespan)
@app.on_event("startup") # never called
async def connect():
app.state.redis = redis.from_url("redis://localhost:6379")
Fix: put all startup and shutdown work in the one lifespan function and remove the on_event handlers. on_event is deprecated in favor of lifespan, so there is no reason to keep both.
Lifespan state is on request.state
Lifespan can yield a dict. Starlette makes that dict available per request as request.state, and it does not touch app.state.
@asynccontextmanager
async def lifespan(app: FastAPI):
client = redis.from_url("redis://localhost:6379")
yield {"redis": client} # available as request.state.redis
await client.aclose()
@app.get("/items/{item_id}")
async def read_item(item_id: int, request: Request):
return await request.app.state.redis.get(...) # AttributeError
# Fix: request.state.redis
Pick one style per project. Assigning to app.state inside lifespan works with every supported version; yielding a dict gives you typed-friendly per-request access but requires reading from request.state.
The attribute was set on a different app
request.app is the application handling the request. With app.mount("/sub", sub_app), requests to the mounted app see sub_app as request.app, and a lifespan defined on the parent does not run for it.
parent = FastAPI(lifespan=lifespan) # sets parent.state.redis
sub = FastAPI()
parent.mount("/sub", sub)
@sub.get("/ping")
async def ping(request: Request):
return await request.app.state.redis.ping() # request.app is sub
Fix: assign the attribute on sub as well, or pass the client through a dependency that reads it from the parent app you hold a reference to, rather than relying on request.app.
Reading a long trace
The frames from starlette/middleware/errors.py through fastapi/routing.py are framework code. The frame that matters is the first one under your own package, here app/routes/items.py line 14, which shows the exact app.state.<name> that was missing. Pasting the trace into the Debugly formatter collapses the framework frames so that line stands out.
For another failure that depends on startup objects, see FastAPI Redis connection error troubleshooting.