LearnerJS
LearnerJS

Reputation: 299

How do we build an API using fastAPI that just triggers another Python file executing a query, without waiting for it's response?

This is my current code that waits for the response. details is basically the file imported whose get_query_status method is being called.

@app.get("/trigger_query")
def trigger_query(database:str, entity_name, token: str = Depends(oath2_scheme)):
    value = details.get_query_status(database, entity_name)
    if value is None:
        return HTTPException(status_code= 404, detail= value[1])
    return {'status_code': 200, 'detail': value}

I understand how we can create APIs using fastAPIs, but it always returns success once the query execution is complete.

What would be the way to approach without waiting for it's response? A code demonstration would be helpful.

Upvotes: 0

Views: 1678

Answers (1)

metro2012
metro2012

Reputation: 181

If you want a simple solution without celery you can use background tasks.

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def trigger_query_wrapper(database, entity_name):
    value = details.get_query_status(database, entity_name)
    # add logic for doing something with the value


@app.get("/trigger_query")
async def trigger_query(database:str, entity_name,  background_tasks: BackgroundTasks, token: str = Depends(oath2_scheme)):
    background_tasks.add_task(trigger_query_wrapper,database, entity_name)
    return {"message": "Task triggered in the background"}

See the docs for more details

Upvotes: 2

Related Questions