'Python FastAPI backend get request path operation function access data saved outside of the function

I am quite new to FastAPI, so I have a question if it is possible to access data within the path operation function, which(data) is stored/generated outside of that function.

Generally, API endpoints look like this:

@app.get('/root'):
def some_function(params):
   get_data() # data outside of this function
   .... (some processing)
   return data

The system, I'm trying to make, consists of two independently operating scripts. And they communicate using MQTT Broker. So, I intend to return data(received from other script) and return it through API endpoint.

Any help would be appreciated.



Solution 1:[1]

Sure, you it can do it, just take a look in this example:

data_outside_your_function = 1

@app.get('/root'):
def some_function(params):
   # ignore params for this case
   return data_outside_your_function 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ziur Olpa