Fetching API Data in Streamlit

Hi ,

i am currently running the app locally,

Versions:
Python – 3.12
Streamlit – 1.33

This below code takes 2 seconds for each request. can it be optimized

def fetch_data():   
    style_info = []
    try:
        if ss.input_bi:
            item_response = requests.get(f"{API_URL}/info/?receiver_code={ss.dst}&sender_code={ss.src}&grt={ss.grt}&barcode={ss.input_bi}")            

            if item_response.status_code != 200:
                item_response = requests.get(f"{API_URL}/stock_info/?sender_code={ss.src}&barcode={ss.input_bi}")
            
            if item_response.status_code == 200:
                style_info = item_response.json()
            else:
                style_info = {'barcode': ss.input_bi,"imageurl":"web_image_url"}
    except:
        pass

It check in first api (info), if data not found it check in 2nd api (stock_info) else default value.

Have you tried concurrently making requests to both endpoints. If info endpoint fails at least you already made a request in stock_info.

However, if stock info returns first and successful, now you will have to wait for the status of info because it is your priority.

You will have to be familiar on the api host rules, limits, etc. How fast the host can respond given some requests at close interval?

How critical is the time in this app in getting this data?

Sometimes a clean code is better than a complicated one that runs faster for a small time difference.

@ferdy, Thanks for response. I was creating kind of scanning tool. Where end user select few dropdowns and scan the barcode.

So if it data found in info api, it takes 2 seconds to fetch data and 2 seconds to display the data.
if data not found, it check in stock_api again it takes 2 seconds to fetch data in total 5-6 seconds for each time fetching data

Ill try the solution which you have provided (concurrently making requests) .

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.