0

I have 2 different endpoints

from fastapi import APIRouter

router = APIRouter()


@router.get("/endpoint_1")
async def endpoint_1(attributes):
    interim_data = await get_interim_data() # performs heavy search
    result = process_data_1(interim_data)
    return result


@router.get("/endpoint_2")
async def endpoint_2():
    interim_data = await get_interim_data() # performs heavy search
    result = process_data_2(interim_data)
    return result

Both endpoints call the same function to get initial data but further usage of that data is different. If requests to endpoint_1 and endpoint_2 are created at the same time, how can I make it so that get_interim_data would only be called once?

Robert Axe
  • 396
  • 2
  • 11
  • You can cache the result, look it here https://stackoverflow.com/questions/74360992/how-to-cache-data-in-fastapi – Henrique Andrade Apr 06 '23 at 18:31
  • You can calculate your data once [on startup](https://fastapi.tiangolo.com/advanced/events/#startup-event) and store the result in global scope variable – sudden_appearance Apr 06 '23 at 18:48
  • @HenriqueAndrade I don't think cache will help as `get_interim_data` will be called in both endpoints before it is stored in cache – Robert Axe Apr 06 '23 at 21:06
  • @sudden_appearance `get_interim_data` depends on parameters passed, so it is not possible to precalculate – Robert Axe Apr 06 '23 at 21:07

0 Answers0