DEV Community

h2L
h2L

Posted on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay