Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does async actually do in FastAPI? [duplicate]

I have two scripts:

from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/")
async def root():
    a = await asyncio.sleep(10)
    return {'Hello': 'World',}

And second one:

from fastapi import FastAPI
import time
  
app = FastAPI()

@app.get("/")
def root():
    a = time.sleep(10)
    return {'Hello': 'World',}

Please note the second script doesn't use async. Both scripts do the same, at first I thought, the benefit of an async script is that it allows multiple connections at once, but when testing the second code, I was able to run multiple connections as well. The results are the same, performance is the same and I don't understand why would we use async method. Would appreciate your explanation.

like image 876
filtertips Avatar asked Feb 27 '26 08:02

filtertips


1 Answers

FastAPI Docs:

You can mix def and async def in your path operation functions as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.

Anyway, in any of the cases above, FastAPI will still work asynchronously and be extremely fast.

Both endpoints will be executed asynchronously, but if you define your endpoint function asynchronously, it will allow you to use await keyword and work with asynchronous third party libraries

like image 174
roma Avatar answered Feb 28 '26 21:02

roma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!