From the course: Build REST APIs with FastAPI

Unlock this course with a free trial

Join today to access over 24,200 courses taught by industry experts.

Async handlers

Async handlers

FastAPI utilizes asyncio and can have async handlers. Asyncio is a Python library that helps you write concurrent code for I/O-bound workloads, meaning most of the time your handlers are working with the network. It is great. I'm not going to go into it because this is a whole course by itself. Asyncio is efficient, but you need to be really careful. It works on a single thread and if you, without knowing, doing something which is blocking, and if you're blocking even without knowing, you're not blocking only your request, you're blocking every request on the server. The FastAPI documentation is really great, and there's a great section about concurrency and asyncio. But I want to show you an example of what can happen. So here's the code. And I'm having three handler, /sleep/sys is going to be non-async handler, just a regular handler, and it uses the system sleep which is blocking. The second one which is /sleep/async-sys, it's an async handler, but it's using the system sleep which…

Contents