-1

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.

  • 1
    There isn't anything magic about running your code in a view endpoint - calling external functions is fine. Did you experience something else? – MatsLindh May 06 '22 at 08:56
  • Data is updated continuously and i need to listen to mqtt channel. But if i want to call external function, i should predefine it before path operation function – Dastan Zhumazhanov May 06 '22 at 11:24
  • What's the issue with calling `get_data` as in your example? – MatsLindh May 06 '22 at 11:26
  • In case you had to define the endpoint with `async def` and execute some CPU-bound operation (as you show `some processing` is taking place inside), please have a look at [this answer](https://stackoverflow.com/a/71517830/17865804). Otherwise, as noted by @MatsLindh, calling external functions is fine. – Chris May 06 '22 at 11:29
  • In that case, get_data() function can not access data defined later on, in __name__==“__main__” thread. – Dastan Zhumazhanov May 07 '22 at 14:38

1 Answers1

0

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 
Ziur Olpa
  • 878
  • 1
  • 6
  • 20