Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)
`async def` vs standard `def` in FastAPI endpoints:
In Simple Words:
async def: Runs directly on the main AsyncIO event loop thread. Use when callingawaiton non-blocking async libraries.- Standard
def: FastAPI automatically offloads standarddefroutes to an internal worker thread pool, preventing blocking code from freezing the event loop!
python
# Use standard def for legacy synchronous blocking libraries:
import time
@app.get("/sync-task")
def sync_endpoint():
time.sleep(1) # Safe: FastAPI offloads this to an external thread pool!
return {"status": "completed"}