Advanced Dashboard Interactivity with Streamlit + APIs
Learn how to build advanced interactive dashboards using Streamlit + APIs. From live data to user actions, make dashboards feel like SaaS apps.
Hook: The Problem with “Static Dashboards” Dashboards are everywhere. From startup founders showing KPIs to ML engineers monitoring models, everyone loves a clean Streamlit dashboard. But let’s be real: most dashboards are static. You pull data, render a chart, and call it a day. Nice for a demo, useless for real-time decision-making. The future isn’t static dashboards. It’s interactive dashboards powered by APIs — dashboards that fetch live data, trigger backend workflows, and even act like lightweight SaaS products. And Streamlit in 2025 makes this easier than ever.
Why Streamlit + APIs Is a Game-Changer On its own, Streamlit is great for prototyping. But when you pair it with APIs, you get dashboards that:
- Fetch real-time stock prices, weather, IoT feeds
- Trigger long-running jobs (model retraining, ETL, report generation)
- Act as a frontend for microservices
- Feel more like a SaaS app than a “data notebook with charts”
Let’s walk through concrete patterns — and yes, lots of code.
Pattern 1: Pulling Live Data via REST API Suppose you want a dashboard for cryptocurrency prices. Here’s the boring version: load a CSV. Here’s the real version: pull from a live API.
import streamlit as st
import requests
import pandas as pd
st.title("📈 Live Crypto Dashboard")
# Simple REST API call
def fetch_prices(symbol="BTCUSDT"):
url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={symbol}"
resp = requests.get(url)
return resp.json()
symbol = st.selectbox("Choose a crypto", ["BTCUSDT", "ETHUSDT", "BNBUSDT"])
data = fetch_prices(symbol)
st.metric("Price", f"${data['lastPrice']}")
st.metric("24h Change", f"{data['priceChangePercent']}%")
st.metric("Volume", data['volume'])
Now every time a user selects a symbol, the dashboard makes a live API call. That tiny trick makes your dashboard feel alive.
Pattern 2: Background Jobs with Async APIs But what if the job takes time — say you’re retraining a model? You don’t want the dashboard freezing while users wait. Enter async APIs.
Imagine a FastAPI backend that kicks off a job:
# backend.py (FastAPI)
from fastapi import FastAPI, BackgroundTasks
import time
app = FastAPI()
def train_model():
time.sleep(10) # fake long job
with open("status.txt", "w") as f:
f.write("done")
@app.post("/train")
def trigger_training(background_tasks: BackgroundTasks):
background_tasks.add_task(train_model)
return {"status": "started"}
Then in Streamlit:
import streamlit as st
import requests
import time
st.title("⚡ Trigger Model Training")
if st.button("Train Model"):
resp = requests.post("http://localhost:8000/train")
st.success("Training started... check status below")
# Poll for status
if st.button("Check Status"):
with open("status.txt") as f:
st.info(f"Training Status: {f.read()}")
This pattern turns a dashboard into a control panel for workflows.
Pattern 3: Streaming Data into Charts Static charts are old news. Streaming charts? That’s next-level.
import streamlit as st
import requests
import time
import pandas as pd
st.title("📡 Live IoT Sensor Data")
chart = st.line_chart([])
for i in range(50): # simulate stream
resp = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
price = resp.json()["bpi"]["USD"]["rate_float"]
new_data = pd.DataFrame({"price": [price]})
chart.add_rows(new_data)
time.sleep(2)
Now your dashboard looks like a Bloomberg terminal.
Pattern 4: Secure APIs with Auth Public dashboards are fun until you realize you’re exposing sensitive endpoints. Enter authentication. Here’s a Streamlit login gate:
import streamlit as st
import requests
st.title("🔐 Secure Dashboard")
API_URL = "http://localhost:8000/protected"
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Login"):
resp = requests.post("http://localhost:8000/login", json={"username": username, "password": password})
if resp.status_code == 200:
token = resp.json()["access_token"]
st.session_state["token"] = token
st.success("Logged in!")
else:
st.error("Invalid credentials")
# Protected call
if "token" in st.session_state:
headers = {"Authorization": f"Bearer {st.session_state['token']}"}
resp = requests.get(API_URL, headers=headers)
st.write(resp.json())
Suddenly your Streamlit app looks like a mini SaaS app with login + API calls.
Pattern 5: Two-Way Dashboards (APIs Write Back) Most dashboards are read-only. But the real world requires write-backs:
- Add a user to CRM
- Update a config
- Send a Slack notification
Example: sending a Slack message from a Streamlit dashboard.
import streamlit as st
import requests
st.title("💬 Send Slack Message")
message = st.text_area("Message to send")
if st.button("Send"):
webhook_url = "https://hooks.slack.com/services/xxx/yyy/zzz"
payload = {"text": message}
resp = requests.post(webhook_url, json=payload)
if resp.status_code == 200:
st.success("Message sent to Slack ✅")
else:
st.error("Failed to send")
This moves dashboards from viewer-only to action-triggering control panels.
Case Study: Turning a Notebook into a SaaS-Like Dashboard I once built a sales forecasting model in a Jupyter notebook. It worked — barely. But the business team didn’t want “run this cell and hope it works.” They wanted a tool.
So I wrapped the model in a FastAPI service and built a Streamlit dashboard that:
- Pulled live sales data from an API
- Let users upload CSVs
- Triggered retraining jobs
- Displayed forecasts in interactive charts
Here’s a simplified slice:
import streamlit as st
import requests
import pandas as pd
st.title("📊 Sales Forecast Dashboard")
# Upload CSV
file = st.file_uploader("Upload Sales Data", type=["csv"])
if file:
df = pd.read_csv(file)
st.write("Uploaded Data:", df.head())
if st.button("Run Forecast"):
resp = requests.post("http://localhost:8000/forecast", json=df.to_dict(orient="records"))
results = resp.json()
st.line_chart(results["forecast"])
What started as a notebook became a tool the sales team used daily.
Extra Tricks for Streamlit + API Power Users
- Caching API calls:
@st.cache_data(ttl=60) def fetch_data(): return requests.get("https://api.example.com/data").json()
- WebSockets for real-time: Streamlit now supports async → connect to WebSocket APIs.
- Session state for auth tokens: persist user sessions across tabs.
- Theming + CSS hacks: Make dashboards look like SaaS products, not academic notebooks.
Closing Thoughts Streamlit started as a data scientist’s toy. But when you add APIs, it becomes something bigger: A way to build real-time, interactive, SaaS-like apps in hours. If you’re still building dashboards that only show static CSVs, you’re missing the future. APIs + Streamlit = dashboards that act, not just display.
Read the full article here: https://medium.com/@hadiyolworld007/advanced-dashboard-interactivity-with-streamlit-apis-f63bead069bf