FastAPI पाथ ऑपरेशन के लिए async def और नियमित def दोनों को सपोर्ट करता है। प्रदर्शन के लिए यह विकल्प महत्वपूर्ण है: async def का उपयोग करें जब आप गैर-ब्लॉकिंग I/O को कर सकें, और नियमित जब आपका कोड ब्लॉकिंग (सिंक्रोनस) ऑपरेशन कॉल करे।
FastAPI पाथ ऑपरेशन के लिए async def और नियमित def दोनों को सपोर्ट करता है। प्रदर्शन के लिए यह विकल्प महत्वपूर्ण है: async def का उपयोग करें जब आप गैर-ब्लॉकिंग I/O को कर सकें, और नियमित जब आपका कोड ब्लॉकिंग (सिंक्रोनस) ऑपरेशन कॉल करे।
awaitdef@app.get("/async")
async def async_endpoint():
data = await fetch_from_api() # await non-blocking I/O — efficient
return data
@app.get("/sync")
def sync_endpoint():
data = blocking_db_call() # ordinary blocking code
return data
async def → runs on the main event loop. Efficient ONLY if you await non-blocking calls.
⚠️ A BLOCKING call inside async def blocks the WHOLE event loop → kills concurrency!
def → FastAPI runs it in a THREAD POOL, so blocking code doesn't block the event loop.
Safe for synchronous/blocking libraries.
# ✅ async def — when you can await async libraries (httpx, async DB drivers)
async def get_user():
async with httpx.AsyncClient() as c:
return await c.get(url)
# ✅ plain def — when using SYNCHRONOUS/blocking libraries (requests, sync ORM)
def get_user():
return requests.get(url).json() # blocking → FastAPI runs it in a thread
# ❌ THE DANGEROUS MISTAKE — blocking call inside async def
async def bad():
return requests.get(url).json() # blocks the event loop! Use `def` or an async client
आलोचनात्मक नियम: कभी भी async def में ब्लॉकिंग कॉल न रखें — यह event loop को ब्लॉक करता है और समानता को नष्ट करता है। या तो await के साथ async लाइब्रेरी का उपयोग करें, या सादा def उपयोग करें (जो FastAPI thread pool में सुरक्षित रूप से चलाता है)।
async def और def के बीच सही विकल्प आपके API के प्रदर्शन और समानता को सीधे प्रभावित करता है, और गलत करना एक आम, गंभीर गलती है।
मुख्य अंतर्दृष्टि यह है कि async def केवल तभी लाभकारी है जब आप गैर-ब्लॉकिंग ऑपरेशन को await करें — एक ब्लॉकिंग कॉल (जैसे सिंक्रोनस requests लाइब्रेरी या ब्लॉकिंग डेटाबेस ड्राइवर) को async def में रखना पूरे event loop को ब्लॉक करता है, सभी समवर्ती अनुरोधों को जमा देता है और async के उद्देश्य को नष्ट करता है।
दूसरी ओर, FastAPI बुद्धिमानी से सादे def endpoints को thread pool में चलाता है, इसलिए सिंक्रोनस/ब्लॉकिंग कोड वहां सुरक्षित है।
इस नियम को समझना — वास्तविक async लाइब्रेरी के साथ async def का उपयोग करें, ब्लॉकिंग कोड के लिए सादा def का उपयोग करें, और कभी भी ब्लॉकिंग कॉल को async def में न मिलाएं — FastAPI endpoints को प्रदर्शन करने वाला लिखने और अवरुद्ध event loop के पीछे सभी अनुरोधों को गलती से क्रमबद्ध करने की सूक्ष्म लेकिन विनाशकारी गलती से बचने के लिए आवश्यक है।