Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Streamlit
https://github.com/streamlit/docs
Admin
Streamlit is an open-source app framework for Machine Learning and Data Science teams to create
...
Tokens:
310,003
Snippets:
1,826
Trust Score:
8.9
Update:
6 days ago
Context
Skills
Chat
Benchmark
88.6
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Streamlit Documentation Streamlit is an open-source Python framework that transforms Python scripts into interactive web applications. It enables data scientists and developers to build beautiful, production-ready data apps in minutes without requiring front-end development expertise. The framework uses a simple, declarative syntax where each Streamlit command adds an element to your app's interface, automatically handling the underlying HTML, CSS, and JavaScript. The core functionality revolves around a reactive execution model where the entire script reruns from top to bottom whenever user interaction occurs. Streamlit provides widgets for user input (buttons, sliders, text inputs), display elements for data visualization (charts, tables, metrics), layout components for organizing content (columns, tabs, sidebars), and state management through Session State and caching decorators. The framework supports multipage apps, real-time updates, authentication, database connections, and custom components. ## Write and Magic Display text, data, and any Python object using `st.write` - Streamlit's Swiss Army knife for output. ```python import streamlit as st import pandas as pd # st.write handles multiple data types automatically st.write("Hello **world**!") st.write(1234) st.write(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) # Magic commands - just reference a variable on its own line "This text is displayed automatically" df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) df # Displays the dataframe ``` ## Text Elements Display formatted text including Markdown, titles, headers, code blocks, and LaTeX. ```python import streamlit as st # Headings and text st.title("My App Title") st.header("Section Header") st.subheader("Subsection") st.caption("This is small caption text") # Markdown with formatting st.markdown("**Bold**, *italic*, and `code`") st.markdown(":red[Colored] and :blue-background[highlighted] text") # Code display st.code(""" def hello(): return "Hello, World!" """, language="python") # LaTeX equations st.latex(r"\int_a^b f(x)dx = F(b) - F(a)") # Divider and HTML st.divider() st.html("<p style='color: blue;'>Custom HTML content</p>") ``` ## Data Display Present data using interactive dataframes, tables, metrics, and JSON viewers. ```python import streamlit as st import pandas as pd # Create sample data df = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'score': [85.5, 92.0, 78.3] }) # Interactive dataframe with sorting and filtering st.dataframe(df, use_container_width=True) # Editable data editor edited_df = st.data_editor(df, num_rows="dynamic") # Static table st.table(df) # Metrics with delta indicators col1, col2, col3 = st.columns(3) col1.metric("Temperature", "70 °F", "1.2 °F") col2.metric("Wind", "9 mph", "-8%") col3.metric("Humidity", "86%", "4%") # JSON display st.json({ "name": "Streamlit", "version": "1.55.0", "features": ["widgets", "charts", "layouts"] }) ``` ## Column Configuration Customize dataframe columns with specialized types like progress bars, images, links, and charts. ```python import streamlit as st import pandas as pd data = pd.DataFrame({ "name": ["Alice", "Bob", "Charlie"], "progress": [0.8, 0.5, 0.95], "rating": [4, 3, 5], "website": ["https://example.com"] * 3, "trend": [[1, 2, 4, 8], [8, 4, 2, 1], [2, 4, 6, 8]] }) st.dataframe( data, column_config={ "name": st.column_config.TextColumn("Name", width="medium"), "progress": st.column_config.ProgressColumn( "Completion", min_value=0, max_value=1, format="%.0f%%" ), "rating": st.column_config.NumberColumn( "Rating", format="%d ⭐" ), "website": st.column_config.LinkColumn("Website"), "trend": st.column_config.LineChartColumn("Trend") }, hide_index=True ) ``` ## Charts Create visualizations with built-in charts and integrate with popular libraries like Altair, Plotly, and Matplotlib. ```python import streamlit as st import pandas as pd import numpy as np # Sample data chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['A', 'B', 'C'] ) # Built-in simple charts st.line_chart(chart_data) st.area_chart(chart_data) st.bar_chart(chart_data) st.scatter_chart(chart_data) # Map visualization map_data = pd.DataFrame({ 'lat': [37.76, 37.77, 37.78], 'lon': [-122.4, -122.41, -122.42] }) st.map(map_data) # Matplotlib integration import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.hist(np.random.randn(100), bins=20) st.pyplot(fig) # Altair integration import altair as alt c = alt.Chart(chart_data.reset_index()).mark_circle().encode( x='index', y='A', size='B', color='C' ) st.altair_chart(c, use_container_width=True) ``` ## Input Widgets - Buttons and Selection Capture user input with buttons, checkboxes, radio buttons, and selection widgets. ```python import streamlit as st # Buttons if st.button("Click me"): st.write("Button clicked!") # Download button st.download_button( label="Download data", data="column1,column2\nvalue1,value2", file_name="data.csv", mime="text/csv" ) # Link button st.link_button("Go to Streamlit", "https://streamlit.io") # Checkbox and toggle agree = st.checkbox("I agree to the terms") on = st.toggle("Enable feature") # Radio and selectbox choice = st.radio("Pick one", ["Option A", "Option B", "Option C"]) option = st.selectbox("Select an option", ["Cat", "Dog", "Bird"]) # Multiselect selections = st.multiselect( "Choose colors", ["Red", "Green", "Blue", "Yellow"], default=["Red", "Blue"] ) # Pills and segmented control tag = st.pills("Tags", ["Sports", "Tech", "News"]) filter_option = st.segmented_control("Filter", ["All", "Open", "Closed"]) ``` ## Input Widgets - Numeric and Text Handle numeric input with sliders and number inputs, and text input with various field types. ```python import streamlit as st from datetime import datetime, date, time # Sliders age = st.slider("Select your age", 0, 100, 25) values = st.slider("Select a range", 0.0, 100.0, (25.0, 75.0)) size = st.select_slider("Pick a size", options=["S", "M", "L", "XL"]) # Number input quantity = st.number_input("Enter quantity", min_value=0, max_value=100, value=10, step=1) # Text inputs name = st.text_input("Enter your name", placeholder="John Doe") bio = st.text_area("Tell us about yourself", height=150) # Date and time inputs birthday = st.date_input("Your birthday", date(1990, 1, 1)) meeting_time = st.time_input("Meeting time", time(9, 0)) event_datetime = st.datetime_input("Schedule event") # Color picker color = st.color_picker("Pick a color", "#FF5733") # File uploader uploaded_file = st.file_uploader("Upload a file", type=["csv", "txt", "pdf"]) if uploaded_file is not None: st.write(f"Uploaded: {uploaded_file.name}") # Camera input photo = st.camera_input("Take a picture") ``` ## Chat Elements Build conversational interfaces with chat messages and input for LLM-powered applications. ```python import streamlit as st # Initialize chat history in session state if "messages" not in st.session_state: st.session_state.messages = [] # Display chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Chat input if prompt := st.chat_input("What's on your mind?"): # Add user message to history st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # Generate assistant response with st.chat_message("assistant"): response = f"You said: {prompt}" st.markdown(response) st.session_state.messages.append({"role": "assistant", "content": response}) # Chat message with custom avatar with st.chat_message("assistant", avatar="🤖"): st.write("Hello! How can I help you today?") ``` ## Layouts and Containers Organize your app with columns, tabs, sidebars, expanders, and containers. ```python import streamlit as st # Sidebar with st.sidebar: st.title("Settings") theme = st.selectbox("Theme", ["Light", "Dark"]) st.slider("Font size", 10, 24, 14) # Columns with different widths col1, col2, col3 = st.columns([2, 1, 1]) with col1: st.header("Main Content") st.write("This column is wider") with col2: st.metric("Users", "1,234") with col3: st.metric("Revenue", "$5,678") # Tabs tab1, tab2, tab3 = st.tabs(["Overview", "Data", "Settings"]) with tab1: st.write("Overview content here") with tab2: st.write("Data content here") with tab3: st.write("Settings content here") # Expander with st.expander("Click to expand"): st.write("Hidden content revealed!") st.image("https://placekitten.com/300/200") # Container for grouping elements with st.container(border=True): st.write("This is inside a bordered container") st.button("Contained button") # Popover with st.popover("Open popover"): st.write("Popover content") st.checkbox("Enable option") # Empty placeholder for dynamic content placeholder = st.empty() placeholder.text("This will be replaced") placeholder.success("Content updated!") ``` ## Status and Progress Display progress indicators, spinners, status messages, and notifications. ```python import streamlit as st import time # Progress bar progress_bar = st.progress(0, text="Processing...") for i in range(100): time.sleep(0.01) progress_bar.progress(i + 1, text=f"Processing... {i+1}%") st.success("Complete!") # Spinner with st.spinner("Loading data..."): time.sleep(2) st.success("Data loaded!") # Status container with st.status("Downloading data...", expanded=True) as status: st.write("Searching for data...") time.sleep(1) st.write("Found dataset") time.sleep(1) st.write("Downloading...") time.sleep(1) status.update(label="Download complete!", state="complete", expanded=False) # Alert messages st.success("Operation successful!") st.info("This is an informational message") st.warning("Warning: Check your input") st.error("An error occurred") st.exception(ValueError("Example exception")) # Toast notifications st.toast("Task completed!", icon="✅") # Celebratory effects if st.button("Celebrate!"): st.balloons() # or st.snow() ``` ## Session State Persist data across reruns using Session State for stateful applications. ```python import streamlit as st # Initialize session state if 'counter' not in st.session_state: st.session_state.counter = 0 if 'items' not in st.session_state: st.session_state.items = [] # Increment counter if st.button("Increment"): st.session_state.counter += 1 st.write(f"Counter: {st.session_state.counter}") # Add items to a list new_item = st.text_input("Add item") if st.button("Add"): if new_item: st.session_state.items.append(new_item) st.write("Items:", st.session_state.items) # Callback example def on_change(): st.session_state.greeting = f"Hello, {st.session_state.name_input}!" st.text_input("Enter your name", key="name_input", on_change=on_change) if 'greeting' in st.session_state: st.write(st.session_state.greeting) # Widget with session state key slider_val = st.slider("Value", 0, 100, key="my_slider") st.write(f"Slider value from session state: {st.session_state.my_slider}") ``` ## Caching Optimize performance by caching data and resources to avoid redundant computations. ```python import streamlit as st import pandas as pd import time # Cache data - for dataframes, API calls, computations @st.cache_data(ttl=3600) # Cache for 1 hour def load_data(url): """Load data from URL with caching""" time.sleep(2) # Simulate slow operation return pd.read_csv(url) @st.cache_data def expensive_computation(n): """Cache expensive calculations""" time.sleep(2) return sum(i**2 for i in range(n)) # Cache resources - for ML models, database connections @st.cache_resource def load_model(): """Load ML model once and reuse across sessions""" # model = load_your_model() return {"model": "placeholder"} @st.cache_resource def init_connection(): """Initialize database connection""" # return database.connect() return {"connection": "placeholder"} # Usage if st.button("Load Data"): df = load_data("https://example.com/data.csv") st.dataframe(df) result = expensive_computation(1000) st.write(f"Result: {result}") # Clear cache if st.button("Clear All Cache"): st.cache_data.clear() st.cache_resource.clear() st.success("Cache cleared!") ``` ## Forms Group multiple widgets together and submit them as a batch to avoid intermediate reruns. ```python import streamlit as st # Basic form with st.form("my_form"): st.write("Registration Form") name = st.text_input("Name") email = st.text_input("Email") age = st.number_input("Age", min_value=0, max_value=120, value=25) col1, col2 = st.columns(2) with col1: agree = st.checkbox("I agree to terms") with col2: subscribe = st.checkbox("Subscribe to newsletter") # Form submit button submitted = st.form_submit_button("Submit") if submitted: if not agree: st.error("You must agree to the terms") else: st.success(f"Thank you, {name}! Registration complete.") # Form with callback def handle_submission(): st.session_state.form_submitted = True with st.form("callback_form"): st.text_input("Feedback", key="feedback") st.slider("Rating", 1, 5, 3, key="rating") st.form_submit_button("Submit Feedback", on_click=handle_submission) if st.session_state.get("form_submitted"): st.write(f"Feedback: {st.session_state.feedback}") st.write(f"Rating: {st.session_state.rating}") ``` ## Fragments Define reusable UI components that can rerun independently from the main script. ```python import streamlit as st import time # Fragment that reruns independently @st.fragment def live_metrics(): """This fragment can rerun without affecting the rest of the app""" import random col1, col2 = st.columns(2) with col1: st.metric("CPU", f"{random.randint(20, 80)}%") with col2: st.metric("Memory", f"{random.randint(40, 90)}%") if st.button("Refresh Metrics"): st.rerun(scope="fragment") # Auto-refreshing fragment @st.fragment(run_every="5s") def auto_refresh_data(): """Automatically refresh every 5 seconds""" st.write(f"Last updated: {time.strftime('%H:%M:%S')}") # Display real-time data here st.title("Dashboard") st.write("This content doesn't rerun when fragments update") live_metrics() auto_refresh_data() ``` ## Dialogs Create modal dialogs for focused interactions that overlay the main app content. ```python import streamlit as st # Define a dialog @st.dialog("Settings") def settings_dialog(): st.write("Configure your preferences") theme = st.selectbox("Theme", ["Light", "Dark", "Auto"]) notifications = st.toggle("Enable notifications") if st.button("Save"): st.session_state.theme = theme st.session_state.notifications = notifications st.rerun() # Open dialog with button if st.button("Open Settings"): settings_dialog() # Dialog with data input @st.dialog("Add New Item") def add_item_dialog(): name = st.text_input("Item name") quantity = st.number_input("Quantity", min_value=1, value=1) col1, col2 = st.columns(2) with col1: if st.button("Cancel"): st.rerun() with col2: if st.button("Add"): if name: st.session_state.setdefault('inventory', []).append({ 'name': name, 'quantity': quantity }) st.rerun() if st.button("Add Item"): add_item_dialog() ``` ## Navigation and Multipage Apps Build multipage applications with structured navigation menus. ```python import streamlit as st # Define pages home = st.Page("pages/home.py", title="Home", icon="🏠") dashboard = st.Page("pages/dashboard.py", title="Dashboard", icon="📊") settings = st.Page("pages/settings.py", title="Settings", icon="⚙️") # Configure navigation with sections pg = st.navigation({ "Main": [home, dashboard], "Account": [settings] }) # Run the selected page pg.run() # Alternative: Define page inline @st.Page def about_page(): st.title("About") st.write("This is the about page") # Page links for custom navigation st.page_link("pages/home.py", label="Go to Home", icon="🏠") st.page_link("pages/dashboard.py", label="Dashboard") # Programmatic navigation if st.button("Go to Settings"): st.switch_page("pages/settings.py") ``` ## Database Connections Connect to databases and APIs with built-in connection management and caching. ```python import streamlit as st # SQL Connection conn = st.connection('my_database', type='sql') # Query with caching (1 hour TTL) df = conn.query('SELECT * FROM users LIMIT 10', ttl=3600) st.dataframe(df) # Snowflake connection snow_conn = st.connection('snowflake') df = snow_conn.query('SELECT * FROM my_table') # Using secrets for credentials # .streamlit/secrets.toml: # [connections.my_database] # dialect = "mysql" # host = "localhost" # port = 3306 # database = "mydb" # username = "user" # password = "password" # Access secrets directly api_key = st.secrets["api_key"] db_config = st.secrets["connections"]["my_database"] ``` ## Page Configuration Configure page title, favicon, layout, and other app-wide settings. ```python import streamlit as st # Must be the first Streamlit command st.set_page_config( page_title="My Awesome App", page_icon="🚀", layout="wide", # or "centered" initial_sidebar_state="expanded", # or "collapsed", "auto" menu_items={ 'Get Help': 'https://docs.streamlit.io', 'Report a bug': 'https://github.com/streamlit/streamlit/issues', 'About': '# My App\nBuilt with Streamlit' } ) # App logo st.logo("logo.png", link="https://streamlit.io") st.title("My Configured App") ``` ## Authentication Implement user authentication with OpenID Connect providers. ```python import streamlit as st # Check if user is logged in if not st.user.is_logged_in: st.write("Please log in to continue") st.login() # Shows login button else: st.write(f"Welcome, {st.user.name}!") st.write(f"Email: {st.user.email}") if st.button("Log out"): st.logout() # Access user information if st.user.is_logged_in: user_info = { "name": st.user.name, "email": st.user.email, "is_logged_in": st.user.is_logged_in } st.json(user_info) ``` ## Media Elements Display images, audio, video, and PDF files in your application. ```python import streamlit as st # Images st.image("https://placekitten.com/400/300", caption="A cute kitten") st.image("local_image.png", width=300) # Multiple images in columns col1, col2, col3 = st.columns(3) col1.image("img1.png") col2.image("img2.png") col3.image("img3.png") # Audio st.audio("audio_file.mp3") st.audio("https://example.com/audio.mp3", format="audio/mp3") # Video st.video("video_file.mp4") st.video("https://www.youtube.com/watch?v=VIDEO_ID") # PDF display st.pdf("document.pdf") # Logo in sidebar st.logo("company_logo.png", link="https://company.com") ``` ## App Testing Test Streamlit apps programmatically using the built-in testing framework. ```python from streamlit.testing.v1 import AppTest # Initialize test from file at = AppTest.from_file("streamlit_app.py") at.secrets["API_KEY"] = "test_key" at.run() # Assert no exceptions assert not at.exception # Test widget interactions at.text_input[0].input("test value").run() at.button[0].click().run() at.slider[0].set_value(50).run() at.selectbox[0].select("Option B").run() at.checkbox[0].check().run() # Assert element values assert at.title[0].value == "My App" assert at.success[0].value == "Operation completed!" assert len(at.dataframe) == 1 # Test from string app_code = ''' import streamlit as st st.title("Test App") if st.button("Click"): st.success("Clicked!") ''' at = AppTest.from_string(app_code) at.run() at.button[0].click().run() assert at.success[0].value == "Clicked!" ``` ## Command Line Interface Run and manage Streamlit apps from the terminal. ```bash # Run a Streamlit app streamlit run app.py # Run with custom port and address streamlit run app.py --server.port 8080 --server.address 0.0.0.0 # Run in headless mode (no browser auto-open) streamlit run app.py --server.headless true # Show configuration options streamlit config show # Clear cache streamlit cache clear # Initialize new project streamlit init # Show version streamlit version # Show help streamlit help ``` ## Configuration File Configure Streamlit behavior through `.streamlit/config.toml` file. ```toml # .streamlit/config.toml [server] port = 8501 headless = true enableCORS = false [browser] gatherUsageStats = false [theme] primaryColor = "#FF4B4B" backgroundColor = "#FFFFFF" secondaryBackgroundColor = "#F0F2F6" textColor = "#262730" font = "sans serif" [client] toolbarMode = "minimal" # or "viewer", "developer", "auto" [runner] fastReruns = true ``` ## Summary Streamlit excels at building data-driven applications including dashboards, ML model interfaces, data exploration tools, and internal business applications. The framework's reactive model makes it ideal for rapid prototyping where developers can iterate quickly without managing frontend complexity. Common integration patterns include connecting to databases via `st.connection`, caching expensive computations with `@st.cache_data`, building conversational AI interfaces with chat elements, and creating multipage apps with `st.navigation`. For production deployments, Streamlit apps can be hosted on Streamlit Community Cloud, deployed to cloud platforms like AWS, GCP, or Azure, or containerized with Docker. The framework integrates seamlessly with the Python data science ecosystem including pandas, NumPy, scikit-learn, TensorFlow, and PyTorch. Custom components allow extending functionality with JavaScript libraries, while theming and configuration options enable branding and customization to match organizational requirements.