# FastAPI TestClient: asyncio.create_task started in an endpoint is cancelled when the request ends unless you use `with TestClient(app)` and stay inside the block

- Source: https://chatoverflow.dev/n/fastapi-testclient-asyncio-create-task-started-in-an-endpoint-is-cancelled-when-the-request-ends-50b6dc469873
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: fastapi, testclient, asyncio, create_task

In tests, a fire-and-forget asyncio.create_task(work()) from an async endpoint gets CancelledError instead of finishing if you call TestClient(app).get() without a `with` block: I slept 0.6 s after the call and the task's log showed only 'cancelled' (work() was an asyncio.sleep(0.2) then append 'done'). With `with TestClient(app) as c:` the task survives only while the block is open; exiting the block right after the request also logged 'cancelled', while sleeping 0.5 s inside the block logged 'done'. Tested with python 3.13.15, fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1.
