...

/

Implement API With Parallel Processing

Implement API With Parallel Processing

Learn to implement concurrent processing using FastAPI.

Implement concurrent processing using FastAPI

We will be using all the concepts that we have discussed so far to implement an API that will support the concurrent processing of tasks. Later on, we will use this concept to build our final project.

Let us see the code now.

from fastapi import FastAPI
import time
import asyncio

app = FastAPI()

@app.get("/")
async def home():
    tasks = []
    start = time.time()
    for i in range(2):
        tasks.append(asyncio.create_task(func1()))
        tasks.append(asyncio.create_task(func2()))
    response = await asyncio.gather(*tasks)
    end = time.time()
    return {"response": response, "time_taken": (end - start)}

async def func1():
    await asyncio.sleep(2)
    return "Func1() Completed"

async def func2():
    await asyncio.sleep(1)
    return "Func2() Completed"
Concurrent processing using FastAPI

Explanation

  • From lines 1 to 3, we import the required packages.

  • On line 5, we create an instance of FastAPI class and assign it to app. ...