Managers want a dashboard. Developers want to avoid spending three weeks building a React front end, an API and authentication just to show some charts.
Streamlit sits neatly between a spreadsheet and a full web application. You write a Python script, and Streamlit turns it into an interactive web app with filters, charts and tables. No HTML, CSS or JavaScript required.
In this tutorial we'll build a sales dashboard with KPI cards, filters, charts, a data table and a download button, then look at connecting real data, testing and deployment.
Install
pip install streamlit pandas
The complete dashboard
Your browser opens at localhost:8501 with a working dashboard: city and month filters in the sidebar, three KPI cards, a revenue line chart, an orders bar chart, a data table and a CSV download button.
How Streamlit works
Streamlit's model is unusual but simple: every time the user interacts with a widget, the whole script runs again from top to bottom, with the widget's new value.
That's why the code reads like a normal script:
cities = st.sidebar.multiselect("City", ...)
filtered = df[df["city"].isin(cities)]
st.bar_chart(filtered.groupby("city")["orders"].sum())
Change the city selection, the script re-runs, filtered is recalculated, and the chart updates. You never write event handlers.
Caching data
@st.cache_data(ttl=600)
def load_data():
Because the script re-runs on every interaction, loading data from a database each time would be slow. @st.cache_data stores the result and reuses it. ttl=600 refreshes it every 10 minutes so the dashboard doesn't show stale numbers forever.
Use @st.cache_resource for things like database connections or machine learning models that should be created once and shared.
Layout
- st.set_page_config(layout="wide") uses the full browser width, which suits dashboards.
- st.sidebar holds filters out of the way.
- st.columns(3) places KPI cards side by side; st.columns(2) puts two charts next to each other.
KPI cards
c1.metric("Total orders", f"{filtered['orders'].sum():,}")
st.metric also accepts a delta argument, for example the change from last month, which shows a green or red arrow.
Handling empty selections
if filtered.empty:
st.warning("No data for the selected filters.")
st.stop()
If a user clears all cities, we show a message and stop, instead of drawing empty charts or crashing.
Charts
st.line_chart and st.bar_chart are quick and need no configuration. For more control, such as custom colours, tooltips and annotations, Streamlit supports Altair, Plotly and Matplotlib charts via st.altair_chart, st.plotly_chart and st.pyplot.
Download button
st.download_button("Download CSV", filtered.to_csv(index=False), "sales.csv", "text/csv")
Users can export exactly the filtered data they're looking at. A small touch managers love.
Connecting real data
Replace the sample data with a database query. Streamlit has a built-in connection helper that reads settings from a secrets file:
# .streamlit/secrets.toml (keep this out of Git)
[connections.salesdb]
url = "mssql+pyodbc://user:password@server/SalesDb?driver=ODBC+Driver+18+for+SQL+Server"
conn.query caches results for the given ttl. Always use parameters (:start) rather than building SQL strings from user input.
For larger datasets, aggregate in the database (totals per day, city or product) instead of loading millions of raw rows into pandas.
Testing the dashboard
Streamlit includes a testing framework that runs your app without a browser:
from streamlit.testing.v1 import AppTest
at = AppTest.from_file("dashboard.py").run()
assert not at.exception
print([m.value for m in at.metric]) # ['4,800', '₹6,960,000', '400']
at.sidebar.multiselect[0].set_value(["Kanpur"]).run()
print([m.value for m in at.metric]) # ['1,184', '₹1,716,800', '99']
We ran exactly this test against the dashboard above: it loaded with no exceptions, showed the KPI values for all cities, and updated correctly when the filter changed to Kanpur only. Tests like this catch broken filters and calculation mistakes before your managers do.
Deploying it
On your own server: run streamlit run dashboard.py --server.port 8501 --server.address 127.0.0.1 as a service, and put it behind a reverse proxy (IIS with URL Rewrite and ARR, or Nginx) that provides HTTPS. Streamlit uses WebSockets, so make sure the proxy supports them.
In a container: package it with Docker and run it on any container platform.
Streamlit Community Cloud: free hosting for apps from a GitHub repository, best suited to public or non-sensitive data.
Snowflake: Streamlit is owned by Snowflake, which offers hosting for Streamlit apps inside the Snowflake platform.
Security: don't skip this
A dashboard with sales figures is sensitive. Streamlit doesn't add login protection by default to a self-hosted app.
- Put authentication in front of it: recent Streamlit versions support OpenID Connect sign-in (for example with Google or Microsoft Entra ID) through st.login() and secrets configuration. Alternatively, a reverse proxy with authentication, or a network restricted to your VPN.
- Use a read-only database account that can see only the tables the dashboard needs.
- Keep secrets in secrets.toml or environment variables, never in code.
- Don't expose port 8501 directly to the internet.
When to choose something else
Streamlit is excellent for internal dashboards, data apps, prototypes and tools used by tens or hundreds of people. Consider other options when:
- you need a pixel-perfect, highly branded customer-facing interface
- you have thousands of concurrent users
- business users want to build their own reports (Power BI, Metabase or Apache Superset may suit better)
Start small
With around 80 lines of Python, you have an interactive dashboard with filters, KPIs, charts, a table and CSV export, plus automated tests. Connect it to your database, add authentication, deploy it behind HTTPS, and your team has live numbers without waiting for a monthly Excel report.
Start with the three numbers your managers ask about most, put them on a Streamlit page, and grow it from there.
Leave a Comment