Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Streamlit turns a normal Python script into an interactive browser application. You can build dashboards, data tools, model demos and AI interfaces without writing a separate frontend for the basic workflow. This tutorial takes you from installation to a deployable CSV dashboard, then explains reruns, caching, session state, multipage structure, secrets and production trade-offs.

Streamlit is a strong fit for Python-first, data-centric applications. It is not a universal replacement for a conventional frontend and backend: highly branded consumer sites, complex transactional systems and very large workloads usually need a different architecture.

What is Streamlit?

Streamlit is an open-source Python framework that runs your script, captures Streamlit commands and renders the result in a browser. The framework provides the local web server, widgets, layouts and common data displays, so a basic app needs no hand-written HTML, CSS or JavaScript. See the official documentation and main concepts.

import streamlit as st

st.title("My first Streamlit app")
st.write("Hello from Python!")

Running this script displays a local page with a title and text. Streamlit is particularly useful for dashboards, exploratory analysis, internal tools, machine-learning demos, evaluation interfaces, reports and chat applications.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How Streamlit executes your code

The key idea is the rerun model. After a widget interaction, Streamlit normally executes the script from top to bottom again, then redraws the page.

  1. A user changes a widget or submits an interaction.
  2. The widget’s callback, if any, runs.
  3. The script reruns from the beginning.
  4. Streamlit renders the updated output for that browser session.

Do not expect an ordinary local variable to preserve a value between reruns. Widget keys and st.session_state preserve user-specific values; caching avoids repeating suitable expensive work. A button is true only for the interaction that triggered it, while most widgets return their current value on every run.

Read the current execution guidance in the fundamentals summary.

Install Streamlit and create a project

Prerequisites

  • Basic Python, including imports, functions, lists and dictionaries.
  • A terminal or command prompt and a code editor.
  • A supported Python environment; verify compatibility in the current installation documentation.
  • Optional familiarity with pandas for data work.

Create an isolated environment

mkdir streamlit-demo
cd streamlit-demo
python -m venv .venv

Activate it on macOS or Linux:

source .venv/bin/activate

On Windows PowerShell:

.venvScriptsActivate.ps1

Install and verify

pip install streamlit
python --version
pip show streamlit
streamlit version
streamlit hello

Create app.py in your editor. On macOS or Linux, touch app.py also works. Start the app with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
streamlit run app.py

Streamlit starts a local server and typically opens a browser tab. The exact installed version is more useful than an unverified “latest” number, so check it locally.

Build a minimal app

import streamlit as st

st.set_page_config(
    page_title="Streamlit Demo",
    page_icon="🎈",
    layout="centered",
)

st.title("Streamlit Tutorial")
st.subheader("A small Python web app")
st.write("This interface is rendered from a Python script.")

name = st.text_input("What is your name?")

if name:
    st.success(f"Hello, {name}!")
  • st.title() creates a prominent heading.
  • st.write() displays text and many Python objects.
  • st.text_input() creates an input widget.
  • The conditional block appears only after a name is entered.

Saving the file prompts a rerun or reruns automatically, depending on the current workflow and settings. The official walkthrough is Create an app.

Build a useful CSV dashboard

This complete example accepts a CSV, previews it, finds numeric columns and charts a selected column. It also handles no upload and files without numeric data.

import streamlit as st
import pandas as pd

st.set_page_config(page_title="Sales Dashboard", layout="wide")
st.title("Sales Dashboard")

uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])

if uploaded_file is None:
    st.info("Upload a CSV file to begin.")
    st.stop()

df = pd.read_csv(uploaded_file)

st.subheader("Preview")
st.dataframe(df, use_container_width=True)

numeric_columns = df.select_dtypes(include="number").columns.tolist()

if not numeric_columns:
    st.warning("The file contains no numeric columns for charting.")
    st.stop()

column = st.selectbox("Choose a numeric column", numeric_columns)
st.subheader(f"Distribution of {column}")
st.bar_chart(df[column].value_counts().sort_index())

An uploaded file is temporary input, not an automatic database. Use a database, object store or another external service when records must survive sessions or restarts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Widgets, forms and layout

Common input controls

import streamlit as st

st.header("Widget examples")
age = st.number_input("Age", min_value=0, max_value=120, value=30)
department = st.selectbox("Department", ["Sales", "Marketing", "Engineering"])
tags = st.multiselect("Interests", ["Python", "Data", "AI", "Visualization"])
agree = st.checkbox("I agree")

if st.button("Submit"):
    if not agree:
        st.error("Please confirm the checkbox.")
    else:
        st.success(f"Submitted: age={age}, department={department}, interests={tags}")

Other built-in controls include st.radio, st.slider, st.text_input, st.text_area, st.date_input, st.file_uploader, st.data_editor and st.download_button.

Batch related inputs with a form

with st.form("profile_form"):
    username = st.text_input("Username")
    department = st.selectbox("Department", ["Sales", "Engineering", "Support"])
    submitted = st.form_submit_button("Save")

if submitted:
    if not username.strip():
        st.error("Username is required.")
    else:
        st.success(f"Saved profile for {username}.")

Forms are useful for searches, grouped filters, expensive calculations and multi-field submissions because widgets inside them do not trigger the operation independently.

Arrange the page

st.sidebar.header("Filters")
show_details = st.sidebar.checkbox("Show details", value=True)

left, right = st.columns(2)
with left:
    st.metric("Revenue", "$125,000")
with right:
    st.metric("Orders", "2,480", delta="8.4%")

tab1, tab2 = st.tabs(["Overview", "Raw data"])
with tab1:
    st.write("Summary content goes here.")
with tab2:
    st.write("Detailed content goes here.")

if show_details:
    with st.expander("How this was calculated"):
        st.write("Calculation notes.")

Columns, tabs and expanders improve usability; they do not create independent routes or execution contexts. See the layout API.

Display data and charts

For tabular output, use st.dataframe(df) for an interactive table and st.table(df.head()) for a static one. Built-in chart methods include:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
st.line_chart(df)
st.bar_chart(df)
st.area_chart(df)
st.scatter_chart(df)
st.map(df)

Plotly, Altair, Matplotlib, PyDeck and Graphviz can provide richer visualizations. Their event handling, browser behavior and deployment requirements differ, so test the chosen library in the target environment. The API reference lists current options.

Control reruns with caching and session state

Cache computed data

import streamlit as st
import pandas as pd

@st.cache_data
def load_data(path):
    return pd.read_csv(path)

Use st.cache_data for serializable results such as transformed data, API responses, query results and computed values. Cached results can become stale, consume memory or require invalidation, so include all relevant function arguments and use a suitable TTL when freshness matters.

Cache reusable resources

import streamlit as st

@st.cache_resource
def load_model():
    return create_model()

st.cache_resource is intended for expensive-to-initialize reusable objects such as models, database connections, clients and tokenizers. Consider whether the object is mutable or safe to share, and account for memory, concurrency and cold-start time. Neither decorator replaces a database, queue or durable state system. See caching concepts.

Preserve values for one session

import streamlit as st

if "count" not in st.session_state:
    st.session_state.count = 0

if st.button("Increment"):
    st.session_state.count += 1

st.write(f"Count: {st.session_state.count}")

Session state persists across reruns within one browser session. It is not shared automatically with other users and is not durable across session loss, process restarts or deployments. Store durable records externally. The session-state API documents supported patterns.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Use callbacks deliberately

import streamlit as st

def reset():
    st.session_state.name = ""

if "name" not in st.session_state:
    st.session_state.name = ""

st.text_input("Name", key="name")
st.button("Reset", on_click=reset)
st.write("Current value:", st.session_state.name)

The callback runs before the subsequent full rerun. This ordering is useful for reset buttons, wizard steps and chat histories.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Organize a multipage app

my_app/
├── streamlit_app.py
└── pages/
    ├── 1_Overview.py
    └── 2_Data.py
streamlit run streamlit_app.py

The main script is the entry point. Files in pages/ become pages, and numeric prefixes can influence their display order. Put shared functions in deliberate utility modules and plan how session state is shared between pages. For more navigation control, verify the modern navigation APIs against the documentation for your installed version. See multipage tutorials.

Keep secrets out of source code

For local development, create .streamlit/secrets.toml:

api_key = "replace-me"
import streamlit as st
api_key = st.secrets["api_key"]
  • Add .streamlit/secrets.toml to .gitignore.
  • Use the host’s secret-management interface after deployment.
  • Never print credentials in logs or expose private keys to the browser.
  • Separate development, staging and production credentials.
  • Rotate a key immediately if it is committed publicly.

See secrets management.

Connect an API or database safely

import streamlit as st
import requests

@st.cache_data(ttl=300)
def get_data():
    response = requests.get(
        "https://api.example.com/data",
        timeout=20,
    )
    response.raise_for_status()
    return response.json()

try:
    st.json(get_data())
except requests.RequestException as exc:
    st.error(f"Could not load data: {exc}")

Set timeouts, check non-success responses and cache only when five-minute-old data is acceptable. Add retries or a background job for unreliable or slow services. Keep credentials in secrets, and consider a dedicated data-access layer instead of embedding all SQL and network logic in page scripts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Deploy to Streamlit Community Cloud

  1. Put the application in a GitHub repository.
  2. Add a requirements.txt file, for example:
streamlit
pandas
  1. Sign in to Streamlit Community Cloud and choose Deploy an app.
  2. Select the repository and the correct entry-point file.
  3. Configure secrets in the deployment interface.
  4. Inspect logs when startup or runtime errors occur.

For reproducibility, pin versions after testing:

streamlit==<tested-version>
pandas==<tested-version>

Streamlit describes Community Cloud as a free, GitHub-connected platform that handles containerization; hosting, databases, APIs and other infrastructure can still cost money. Its published resource figures (dated February 2024) were approximately 0.078–2 CPU cores, 690 MB–2.7 GB memory and up to 50 GB storage, but the documentation says limits can change. Treat it as convenient managed hosting, not an unlimited production guarantee. See the overview, deployment steps and resource guidance.

Deployment troubleshooting

Symptom Likely cause Fix
ModuleNotFoundError Dependency absent remotely Add it to requirements.txt and redeploy.
Wrong entry point Deployment targets the wrong file Select the actual app script.
Works locally, fails remotely Missing secrets, system dependency, relative path or environment assumption Check logs, configure secrets and use project-relative paths.
Slow startup Model download or heavy initialization at import time Use st.cache_resource, precompute where possible and reduce cold-start work.
Resource error CPU, memory, storage or runtime limit Reduce data/model size or move to infrastructure with suitable capacity.
Blank or broken page Uncaught exception Read deployment logs and reproduce with the same dependency versions.
Missing data file File was not committed or path depends on the working directory Commit required assets and resolve paths from __file__.
Private data exposed Repository or app access is too broad Review access controls; a hidden URL is not authentication.
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
data_path = BASE_DIR / "data" / "sales.csv"

Private apps can restrict viewers through Community Cloud’s documented sign-in and sharing controls; verify current options in the sharing documentation.

Security, scale and durability checks

  • Streamlit does not automatically provide authentication, authorization, row-level security, rate limiting, audit logging, SQL-injection protection or tenant isolation.
  • Session state and caches are not durable business storage.
  • Filter, aggregate or paginate large datasets instead of rendering everything.
  • Long inference, file processing and API calls can block the interface; use progress indicators, caching, precomputation, queues or a separate service where appropriate.
  • Do not cache user-specific secrets, hidden state or mutable objects that users could accidentally share.
  • Model initialization should account for memory, concurrency and cold starts.

When Streamlit is the right choice—and when it is not

Requirement Good direction Why
Python-first dashboard or internal tool Streamlit Fast development with built-in data widgets and charts.
Public machine-learning demo Streamlit or Hugging Face Spaces Convenient model interfaces; review hardware, privacy and usage limits.
Snowflake-centered governed data app Streamlit in Snowflake Integrated access, with Snowflake runtime and warehouse billing; see documentation.
API-first service or background jobs FastAPI Clear service separation and API-oriented architecture.
Conventional full Python application Django Built-in structure for models, authentication, administration and routing.
Highly customized frontend React or Next.js with a backend More control over client state, design systems, routing and interaction.
Alternative Python dashboards Panel or Dash Different component and plotting ecosystems may better match the project.
More hosting control Render or a cloud provider More networking and operational choices, with more configuration responsibility.

Choose Streamlit when built-in widgets are sufficient, server-side reruns are acceptable and the audience is focused. Reconsider it for pixel-perfect marketing sites, native mobile experiences, complex permissions, sophisticated transactional workflows, very high concurrency or strict frontend accessibility and design-system requirements.

Complete project checklist

  • Create and activate a virtual environment.
  • Install and verify Streamlit locally.
  • Run the app with streamlit run.
  • Explain reruns before adding complex interactions.
  • Use forms for grouped submissions and session state for per-session workflow values.
  • Apply st.cache_data and st.cache_resource according to object type and freshness needs.
  • Keep durable records in an external store.
  • Put secrets in configuration, never source code.
  • Pin tested dependencies for deployment.
  • Review logs, resource limits, privacy and access controls before sharing.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.