DEV Community

h2L
h2L

Posted on

How should I go about making multiple concurrent api calls from FastAPI ?

I am currently supporting an API that generates a report for my team using the python framework FastAPI. One of my endpoints makes a call to function called generate which in turn makes 4 calls to the same service to get different pieces of data for the report being built. The extract function is synchronous and takes about 10 - 15 seconds per call to get data.

For now, I would like to keep my '/report' endpoint synchronous but I would like to concurrently make those 4 calls in the generate function below to speed up response times. How should I got about achieving this in FastAPI. Should I spawn threads? Should I use something within the framework to achieve this ?

@app.route('/report')
def fetch_report():
    return report.generate()


 def generate():
  #would like to call these at the same time essentially
  data1 = reporting_datasource.extract(r1)
  data2 = reporting_datasource.extract(r2)
  data3 = reporting_datasource.extract(r3)
  data4 = reporting_datasource.extract(r4)

  return { 
    'part1' : data1,
    'part2' : data2,
    'part3' : data3,
    'part4' : data4
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)