Do I Need to Use async def for Every FastAPI Route?

0
3
Asked By CuriousCoder92 On

I'm new to FastAPI, and my course instructor has written every route handler as an async def, even when using a synchronous SQLAlchemy session. In my mini-project, I've followed this approach and made every route async def, but I'm now confused about whether that's necessary. I'd like to know:

- Should I use just def instead of async def for routes that don't need to be asynchronous?
- Is it bad practice to default to async def even when there's nothing to await inside?
- For my portfolio project, would it seem unprofessional to have async def everywhere?

I'd love to hear how experienced FastAPI developers manage this! Thanks!

1 Answer

Answered By TechSavvy123 On

FastAPI automatically handles def and async def differently. If you use async def, it operates in the event loop, which means you need to avoid blocking calls. On the other hand, using def runs it in a thread, which means you don't have to worry about blocking in the same way. So, if you're sticking to synchronous operations, using def is perfectly fine and may be safer. Just know that if you're using async def without any awaits, you're skipping the benefits of async altogether!

CodeNerd87 -

That’s a great point! Also, since Python has the GIL, blocking can happen with sync functions too, so async makes your wait behavior clearer.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.