API reference
Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples.
Browse our API below and click to learn more about any of our available commands! 🎈
Display almost anything
st.write
Write arguments to the app.
st.write("Hello **world**!")
st.write(my_data_frame)
st.write(my_mpl_figure)
Magic
Any time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write
"Hello **world**!"
my_data_frame
my_mpl_figure
Text elements
Markdown
Display string formatted as Markdown.
st.markdown("Hello **world**!")
Title
Display text in title formatting.
st.title("The app title")
Header
Display text in header formatting.
st.header("This is a header")
Subheader
Display text in subheader formatting.
st.subheader("This is a subheader")
Caption
Display text in small font.
st.caption("This is written small caption text")
Code block
Display a code block with optional syntax highlighting.
st.code("a = 1234")
Preformatted text
Write fixed-width and preformatted text.
st.text("Hello world")
LaTeX
Display mathematical expressions formatted as LaTeX.
st.latex("\int a x^2 \,dx")
Divider
Display a horizontal rule.
st.divider()
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Data elements
Dataframes
Display a dataframe as an interactive table.
st.dataframe(my_data_frame)
Data editor
Display a data editor widget.
edited = st.data_editor(df, num_rows="dynamic")
Column configuration
Configure the display and editing behavior of dataframes and data editors.
st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d")
Static tables
Display a static table.
st.table(my_data_frame)
Metrics
Display a metric in big bold font, with an optional indicator of how the metric changed.
st.metric("My metric", 42, 2)
Dicts and JSON
Display object or string as a pretty-printed JSON string.
st.json(my_dict)
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Chart elements
Simple line charts
Display a line chart.
st.line_chart(my_data_frame)
Simple area charts
Display an area chart.
st.area_chart(my_data_frame)
Simple bar charts
Display a bar chart.
st.bar_chart(my_data_frame)
Scatterplots on maps
Display a map with points on it.
st.map(my_data_frame)
Matplotlib
Display a matplotlib.pyplot figure.
st.pyplot(my_mpl_figure)
Altair
Display a chart using the Altair library.
st.altair_chart(my_altair_chart)
Vega-Lite
Display a chart using the Vega-Lite library.
st.vega_lite_chart(my_vega_lite_chart)
Plotly
Display an interactive Plotly chart.
st.plotly_chart(my_plotly_chart)
Bokeh
Display an interactive Bokeh chart.
st.bokeh_chart(my_bokeh_chart)
PyDeck
Display a chart using the PyDeck library.
st.pydeck_chart(my_pydeck_chart)
GraphViz
Display a graph using the dagre-d3 library.
st.graphviz_chart(my_graphviz_spec)
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Input widgets
Button
Display a button widget.
clicked = st.button("Click me")
Data editor
Display a data editor widget.
edited = st.experimental_data_editor(df, num_rows="dynamic")
Download button
Display a download button widget.
st.download_button("Download file", file)
Checkbox
Display a checkbox widget.
selected = st.checkbox("I agree")
Toggle
Display a toggle widget.
activated = st.toggle("Activate")
Radio
Display a radio button widget.
choice = st.radio("Pick one", ["cats", "dogs"])
Selectbox
Display a select widget.
choice = st.selectbox("Pick one", ["cats", "dogs"])
Multiselect
Display a multiselect widget. The multiselect widget starts as empty.
choices = st.multiselect("Buy", ["milk", "apples", "potatoes"])
Slider
Display a slider widget.
number = st.slider("Pick a number", 0, 100)
Select-slider
Display a slider widget to select items from a list.
size = st.select_slider("Pick a size", ["S", "M", "L"])
Text input
Display a single-line text input widget.
name = st.text_input("First name")
Number input
Display a numeric input widget.
choice = st.number_input("Pick a number", 0, 10)
Text-area
Display a multi-line text input widget.
text = st.text_area("Text to translate")
Date input
Display a date input widget.
date = st.date_input("Your birthday")
Time input
Display a time input widget.
time = st.time_input("Meeting time")
File Uploader
Display a file uploader widget.
data = st.file_uploader("Upload a CSV")
Camera input
Display a widget that allows users to upload images directly from a camera.
image = st.camera_input("Take a picture")
Color picker
Display a color picker widget.
color = st.color_picker("Pick a color")
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Media elements
Image
Display an image or list of images.
st.image(numpy_array)
st.image(image_bytes)
st.image(file)
st.image("https://example.com/myimage.jpg")
Audio
Display an audio player.
st.audio(numpy_array)
st.audio(audio_bytes)
st.audio(file)
st.audio("https://example.com/myaudio.mp3", format="audio/mp3")
Video
Display a video player.
st.video(numpy_array)
st.video(video_bytes)
st.video(file)
st.video("https://example.com/myvideo.mp4", format="video/mp4")
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Layouts and containers
Sidebar
Display items in a sidebar.
st.sidebar.write("This lives in the sidebar")
st.sidebar.button("Click me!")
Columns
Insert containers laid out as side-by-side columns.
col1, col2 = st.columns(2)
col1.write("this is column 1")
col2.write("this is column 2")
Tabs
Insert containers separated into tabs.
tab1, tab2 = st.tabs(["Tab 1", "Tab2"])
tab1.write("this is tab 1")
tab2.write("this is tab 2")
Expander
Insert a multi-element container that can be expanded/collapsed.
with st.expander("Open to see more"):
st.write("This is more content")
Container
Insert a multi-element container.
c = st.container()
st.write("This will show last")
c.write("This will show first")
c.write("This will show second")
Empty
Insert a single-element container.
c = st.empty()
st.write("This will show last")
c.write("This will be replaced")
c.write("This will show first")
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Chat elements
Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately.
st.chat_message
lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input
lets you display a chat input widget so the user can type in a message.
Chat message
Insert a chat message container.
import numpy as np
with st.chat_message("user"):
st.write("Hello 👋")
st.line_chart(np.random.randn(30, 3))
Chat input
Display a chat input widget.
prompt = st.chat_input("Say something")
if prompt:
st.write(f"The user has sent: {prompt}")
Status container
Display output of long-running tasks in a container.
with st.status('Running'):
do_something_slow()
Display progress and status
Progress bar
Display a progress bar.
for i in range(101):
st.progress(i)
do_something_slow()
Spinner
Temporarily displays a message while executing a block of code.
with st.spinner("Please wait..."):
do_something_slow()
Status container
Display output of long-running tasks in a container.
with st.status('Running'):
do_something_slow()
Toast
Briefly displays a toast message in the bottom-right corner.
st.toast('Butter!', icon='🧈')
Balloons
Display celebratory balloons!
do_something()
# Celebrate when all done!
st.balloons()
Snowflakes
Display celebratory snowflakes!
do_something()
# Celebrate when all done!
st.snow()
Error box
Display error message.
st.error("We encountered an error")
Warning box
Display warning message.
st.warning("Unable to fetch image. Skipping...")
Info box
Display an informational message.
st.info("Dataset is updated every day at midnight.")
Success box
Display a success message.
st.success("Match found!")
Exception output
Display an exception.
e = RuntimeError("This is an exception of type RuntimeError")
st.exception(e)
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Control flow
Forms
Create a form that batches elements together with a “Submit" button.
with st.form(key='my_form'):
username = st.text_input("Username")
password = st.text_input("Password")
st.form_submit_button("Login")
Stop execution
Stops execution immediately.
st.stop()
Rerun script
Rerun the script immediately.
st.experimental_rerun()
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Developer tools
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Utilities
Set page title, favicon, and more
Configures the default settings of the page.
st.set_page_config(
page_title="My app",
page_icon=":shark:",
)
Echo
Display some code on the app, then execute it. Useful for tutorials.
with st.echo():
st.write('This code will be printed')
Get help
Display object’s doc string, nicely formatted.
st.help(st.write)
st.help(pd.DataFrame)
Get query parameters
Return the query parameters that are currently showing in the browser's URL bar.
st.experimental_get_query_params()
Set query parameters
Set the query parameters that are shown in the browser's URL bar.
st.experimental_set_query_params(
show_map=True,
selected=["asia"]
)
Mutate charts
Add rows
Append a dataframe to the bottom of the current one in certain elements, for optimized data updates.
element = st.line_chart(df)
element.add_rows(df_with_extra_rows)
State management
Session state
Session state is a way to share variables between reruns, for each user session.
st.session_state['key'] = value
Connections and databases
Third-party components
These are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!
Performance
Cache data
Function decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).
@st.cache_data
def long_function(param1, param2):
# Perform expensive computation here or
# fetch data from the web here
return data
Cache resource
Function decorator to cache functions that return global resources (e.g. database connections, ML models).
@st.cache_resource
def init_model():
# Return a global resource here
return pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
Clear cached data
Clear all in-memory and on-disk data caches.
@st.cache_data
def long_function(param1, param2):
# Perform expensive computation here or
# fetch data from the web here
return data
if st.checkbox("Clear All"):
# Clear values from *all* cache_data functions
st.cache_data.clear()
Clear cached resources
Clear all st.cache_resource
caches.
@st.cache_resource
def init_model():
# Return a global resource here
return pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
if st.checkbox("Clear All"):
# Clear values from *all* cache_resource functions
st.cache_resource.clear()
Connections and databases
Setup your connection
Create a connection
Connect to a data source or API
conn = st.experimental_connection('pets_db', type='sql')
pet_owners = conn.query('select * from pet_owners')
st.dataframe(pet_owners)
Built-in connections
SQLConnection
A connection to a SQL database using SQLAlchemy.
conn = st.experimental_connection('sql')
SnowparkConnection
A connection to Snowflake Snowpark.
conn = st.experimental_connection('snowpark')
Third-party connections
Connection base class
Build your own connection with ExperimentalBaseConnection
.
class MyConnection(ExperimentalBaseConnection[myconn.MyConnection]):
def _connect(self, **kwargs) -> MyConnection:
return myconn.connect(**self._secrets, **kwargs)
def query(self, query):
return self._instance.query(query)
Personalization
User info
st.experimental_user
returns information about the logged-in user of private apps on Streamlit Community Cloud.
if st.experimental_user.email == "foo@corp.com":
st.write("Welcome back, ", st.experimental_user.email)
else:
st.write("You are not authorized to view this page.")
Still have questions?
Our forums are full of helpful information and Streamlit experts.