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! 🎈


st.write

Write arguments to the app.

Python
st.write("Hello **world**!")
st.write(my_data_frame)
st.write(my_mpl_figure)

st.write_stream

Write generators or streams to the app with a typewriter effect.

Python
st.write_stream(my_generator)
st.write_stream(my_llm_stream)

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

Python
"Hello **world**!"
my_data_frame
my_mpl_figure

screenshot

Markdown

Display string formatted as Markdown.

Python
st.markdown("Hello **world**!")
screenshot

Title

Display text in title formatting.

Python
st.title("The app title")
screenshot

Header

Display text in header formatting.

Python
st.header("This is a header")
screenshot

Subheader

Display text in subheader formatting.

Python
st.subheader("This is a subheader")
screenshot

Badge

Display a small, colored badge.

Python
st.badge("New")
screenshot

Caption

Display text in small font.

Python
st.caption("This is written small caption text")
screenshot

Code block

Display a code block with optional syntax highlighting.

Python
st.code("a = 1234")
screenshot

Echo

Display some code in the app, then execute it. Useful for tutorials.

Python
with st.echo():
  st.write('This code will be printed')
screenshot

LaTeX

Display mathematical expressions formatted as LaTeX.

Python
st.latex("\int a x^2 \,dx")
screenshot

Preformatted text

Write fixed-width and preformatted text.

Python
st.text("Hello world")
screenshot

Divider

Display a horizontal rule.

Python
st.divider()

Get help

Display object’s doc string, nicely formatted.

Python
st.help(st.write)
st.help(pd.DataFrame)

Render HTML

Renders HTML strings to your app.

Python
st.html("<p>Foo bar.</p>")

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Annotated text

Display annotated text in Streamlit apps. Created by @tvst.

Python
annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".")
screenshot

Drawable Canvas

Provides a sketching canvas using Fabric.js. Created by @andfanilo.

Python
st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",)
screenshot

Tags

Add tags to your Streamlit apps. Created by @gagan3012.

Python
st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1')

screenshot

Dataframes

Display a dataframe as an interactive table.

Python
st.dataframe(my_data_frame)
screenshot

Data editor

Display a data editor widget.

Python
edited = st.data_editor(df, num_rows="dynamic")
screenshot

Column configuration

Configure the display and editing behavior of dataframes and data editors.

Python
st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d")
screenshot

Static tables

Display a static table.

Python
st.table(my_data_frame)
screenshot

Metrics

Display a metric in big bold font, with an optional indicator of how the metric changed.

Python
st.metric("My metric", 42, 2)
screenshot

Dicts and JSON

Display object or string as a pretty-printed JSON string.

Python
st.json(my_dict)

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Streamlit Folium

Streamlit Component for rendering Folium maps. Created by @randyzwitch.

Python
m = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m)

st_data = st_folium(m, width=725)
screenshot

Pandas Profiling

Pandas profiling component for Streamlit. Created by @okld.

Python
df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv")
pr = df.profile_report()

st_profile_report(pr)
screenshot

Image Coordinates

Get the coordinates of clicks on an image. Created by @blackary.

Python
from streamlit_image_coordinates import streamlit_image_coordinates
value = streamlit_image_coordinates("https://placekitten.com/200/300")

st.write(value)

screenshot

Simple area charts

Display an area chart.

Python
st.area_chart(my_data_frame)
screenshot

Simple bar charts

Display a bar chart.

Python
st.bar_chart(my_data_frame)
screenshot

Simple line charts

Display a line chart.

Python
st.line_chart(my_data_frame)
screenshot

Simple scatter charts

Display a line chart.

Python
st.scatter_chart(my_data_frame)
screenshot

Scatterplots on maps

Display a map with points on it.

Python
st.map(my_data_frame)
screenshot

Matplotlib

Display a matplotlib.pyplot figure.

Python
st.pyplot(my_mpl_figure)
screenshot

Altair

Display a chart using the Altair library.

Python
st.altair_chart(my_altair_chart)
screenshot

Vega-Lite

Display a chart using the Vega-Lite library.

Python
st.vega_lite_chart(my_vega_lite_chart)
screenshot

Plotly

Display an interactive Plotly chart.

Python
st.plotly_chart(my_plotly_chart)
screenshot

Bokeh

Display an interactive Bokeh chart.

Python
st.bokeh_chart(my_bokeh_chart)
screenshot

PyDeck

Display a chart using the PyDeck library.

Python
st.pydeck_chart(my_pydeck_chart)
screenshot

GraphViz

Display a graph using the dagre-d3 library.

Python
st.graphviz_chart(my_graphviz_spec)

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

HiPlot

High dimensional Interactive Plotting. Created by @facebookresearch.

Python
data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}]
hip.Experiment.from_iterable(data).display()
screenshot

ECharts

High dimensional Interactive Plotting. Created by @andfanilo.

Python
from streamlit_echarts import st_echarts
st_echarts(options=options)
screenshot

Streamlit Folium

Streamlit Component for rendering Folium maps. Created by @randyzwitch.

Python
m = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
st_data = st_folium(m, width=725)

screenshot

Button

Display a button widget.

Python
clicked = st.button("Click me")
screenshot

Download button

Display a download button widget.

Python
st.download_button("Download file", file)
screenshot

Form button

Display a form submit button. For use with st.form.

Python
st.form_submit_button("Sign up")
screenshot

Link button

Display a link button.

Python
st.link_button("Go to gallery", url)
screenshot

Page link

Display a link to another page in a multipage app.

Python
st.page_link("app.py", label="Home", icon="🏠")
st.page_link("pages/profile.py", label="My profile")
screenshot

Checkbox

Display a checkbox widget.

Python
selected = st.checkbox("I agree")
screenshot

Color picker

Display a color picker widget.

Python
color = st.color_picker("Pick a color")
screenshot

Feedback

Display a rating or sentiment button group.

Python
st.feedback("stars")
screenshot

Multiselect

Display a multiselect widget. The multiselect widget starts as empty.

Python
choices = st.multiselect("Buy", ["milk", "apples", "potatoes"])
screenshot

Pills

Display a pill-button selection widget.

Python
st.pills("Tags", ["Sports", "AI", "Politics"])
screenshot

Radio

Display a radio button widget.

Python
choice = st.radio("Pick one", ["cats", "dogs"])
screenshot

Segmented control

Display a segmented-button selection widget.

Python
st.segmented_control("Filter", ["Open", "Closed", "All"])
screenshot

Selectbox

Display a select widget.

Python
choice = st.selectbox("Pick one", ["cats", "dogs"])
screenshot

Select-slider

Display a slider widget to select items from a list.

Python
size = st.select_slider("Pick a size", ["S", "M", "L"])
screenshot

Toggle

Display a toggle widget.

Python
activated = st.toggle("Activate")
screenshot

Number input

Display a numeric input widget.

Python
choice = st.number_input("Pick a number", 0, 10)
screenshot

Slider

Display a slider widget.

Python
number = st.slider("Pick a number", 0, 100)
screenshot

Date input

Display a date input widget.

Python
date = st.date_input("Your birthday")
screenshot

Datetime input

Display a datetime input widget.

Python
datetime = st.datetime_input("Schedule your event")
screenshot

Time input

Display a time input widget.

Python
time = st.time_input("Meeting time")
screenshot

Chat input

Display a chat input widget.

Python
prompt = st.chat_input("Say something")
if prompt:
    st.write(f"The user has sent: {prompt}")
screenshot

Text-area

Display a multi-line text input widget.

Python
text = st.text_area("Text to translate")
screenshot

Text input

Display a single-line text input widget.

Python
name = st.text_input("First name")
screenshot

Audio input

Display a widget that allows users to record with their microphone.

Python
speech = st.audio_input("Record a voice message")
screenshot

Data editor

Display a data editor widget.

Python
edited = st.data_editor(df, num_rows="dynamic")
screenshot

File uploader

Display a file uploader widget.

Python
data = st.file_uploader("Upload a CSV")
screenshot

Camera input

Display a widget that allows users to upload images directly from a camera.

Python
image = st.camera_input("Take a picture")

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Tags

Add tags to your Streamlit apps. Created by @gagan3012.

Python
from streamlit_tags import st_tags

st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'],
suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1')
screenshot

Stqdm

The simplest way to handle a progress bar in streamlit app. Created by @Wirg.

Python
from stqdm import stqdm

for _ in stqdm(range(50)):
    sleep(0.5)
screenshot

Timeline

Display a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.

Python
from streamlit_timeline import timeline

with open('example.json', "r") as f:
  timeline(f.read(), height=800)

screenshot

Image

Display an image or list of images.

Python
st.image(numpy_array)
st.image(image_bytes)
st.image(file)
st.image("https://example.com/myimage.jpg")
screenshot

Logo

Display a logo in the upper-left corner of your app and its sidebar.

Python
st.logo("logo.jpg")
screenshot

PDF

Display a PDF file.

Python
st.pdf("my_document.pdf")
screenshot

Audio

Display an audio player.

Python
st.audio(numpy_array)
st.audio(audio_bytes)
st.audio(file)
st.audio("https://example.com/myaudio.mp3", format="audio/mp3")
screenshot

Video

Display a video player.

Python
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. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Drawable Canvas

Provides a sketching canvas using Fabric.js. Created by @andfanilo.

Python
from streamlit_drawable_canvas import st_canvas

st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",)
screenshot

Image Comparison

Compare images with a slider using JuxtaposeJS. Created by @fcakyon.

Python
from streamlit_image_comparison import image_comparison

image_comparison(img1="image1.jpg", img2="image2.jpg",)
screenshot

Streamlit Cropper

A simple image cropper for Streamlit. Created by @turner-anderson.

Python
from streamlit_cropper import st_cropper

st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio)

screenshot

Columns

Insert containers laid out as side-by-side columns.

Python
col1, col2 = st.columns(2)
col1.write("this is column 1")
col2.write("this is column 2")
screenshot

Container

Insert a multi-element container.

Python
c = st.container()
st.write("This will show last")
c.write("This will show first")
c.write("This will show second")
screenshot

Modal dialog

Insert a modal dialog that can rerun independently from the rest of the script.

Python
@st.dialog("Sign up")
def email_form():
    name = st.text_input("Name")
    email = st.text_input("Email")
screenshot

Empty

Insert a single-element container.

Python
c = st.empty()
st.write("This will show last")
c.write("This will be replaced")
c.write("This will show first")
screenshot

Expander

Insert a multi-element container that can be expanded/collapsed.

Python
with st.expander("Open to see more"):
  st.write("This is more content")
screenshot

Popover

Insert a multi-element popover container that can be opened/closed.

Python
with st.popover("Settings"):
  st.checkbox("Show completed")
screenshot

Sidebar

Display items in a sidebar.

Python
st.sidebar.write("This lives in the sidebar")
st.sidebar.button("Click me!")
screenshot

Space

Add vertical or horizontal space.

Python
st.space("small")
screenshot

Tabs

Insert containers separated into tabs.

Python
tab1, tab2 = st.tabs(["Tab 1", "Tab2"])
tab1.write("this is tab 1")
tab2.write("this is tab 2")

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Pydantic

Auto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.

Python
import streamlit_pydantic as sp

sp.pydantic_form(key="my_form",
  model=ExampleModel)
screenshot

Streamlit Pages

An experimental version of Streamlit Multi-Page Apps. Created by @blackary.

Python
from st_pages import Page, show_pages, add_page_title

show_pages([ Page("streamlit_app.py", "Home", "🏠"),
  Page("other_pages/page2.py", "Page 2", ":books:"), ])

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.

screenshot

Chat input

Display a chat input widget.

Python
prompt = st.chat_input("Say something")
if prompt:
    st.write(f"The user has sent: {prompt}")
screenshot

Chat message

Insert a chat message container.

Python
import numpy as np
with st.chat_message("user"):
    st.write("Hello 👋")
    st.line_chart(np.random.randn(30, 3))
screenshot

Status container

Display output of long-running tasks in a container.

Python
with st.status('Running'):
  do_something_slow()

st.write_stream

Write generators or streams to the app with a typewriter effect.

Python
st.write_stream(my_generator)
st.write_stream(my_llm_stream)

screenshot

Progress bar

Display a progress bar.

Python
for i in range(101):
  st.progress(i)
  do_something_slow()
screenshot

Spinner

Temporarily displays a message while executing a block of code.

Python
with st.spinner("Please wait..."):
  do_something_slow()
screenshot

Status container

Display output of long-running tasks in a container.

Python
with st.status('Running'):
  do_something_slow()
screenshot

Toast

Briefly displays a toast message in the bottom-right corner.

Python
st.toast('Butter!', icon='🧈')
screenshot

Balloons

Display celebratory balloons!

Python
do_something()

# Celebrate when all done!
st.balloons()
screenshot

Snowflakes

Display celebratory snowflakes!

Python
do_something()

# Celebrate when all done!
st.snow()
screenshot

Success box

Display a success message.

Python
st.success("Match found!")
screenshot

Info box

Display an informational message.

Python
st.info("Dataset is updated every day at midnight.")
screenshot

Warning box

Display warning message.

Python
st.warning("Unable to fetch image. Skipping...")
screenshot

Error box

Display error message.

Python
st.error("We encountered an error")
screenshot

Exception output

Display an exception.

Python
e = RuntimeError("This is an exception of type RuntimeError")
st.exception(e)

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Custom notification box

A custom notification box with the ability to close it out. Created by @Socvest.

Python
from streamlit_custom_notification_box import custom_notification_box

styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}}
custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo")
screenshot

Streamlit Extras

A library with useful Streamlit extras. Created by @arnaudmiribel.

Python
from streamlit_extras.let_it_rain import rain

rain(emoji="🎈", font_size=54,
  falling_speed=5, animation_length="infinite",)

Log in a user

st.login() starts an authentication flow with an identity provider.

Python
st.login()

Log out a user

st.logout() removes a user's identity information.

Python
st.logout()

User info

st.user returns information about a logged-in user.

Python
if st.user.is_logged_in:
  st.write(f"Welcome back, {st.user.name}!")

screenshot

Navigation

Configure the available pages in a multipage app.

Python
st.navigation({
    "Your account" : [log_out, settings],
    "Reports" : [overview, usage],
    "Tools" : [search]
})
screenshot

Page

Define a page in a multipage app.

Python
home = st.Page(
    "home.py",
    title="Home",
    icon=":material/home:"
)
screenshot

Page link

Display a link to another page in a multipage app.

Python
st.page_link("app.py", label="Home", icon="🏠")
st.page_link("pages/profile.py", label="My profile")

Switch page

Programmatically navigates to a specified page.

Python
st.switch_page("pages/my_page.py")

screenshot

Modal dialog

Insert a modal dialog that can rerun independently from the rest of the script.

Python
@st.dialog("Sign up")
def email_form():
    name = st.text_input("Name")
    email = st.text_input("Email")

Forms

Create a form that batches elements together with a “Submit" button.

Python
with st.form(key='my_form'):
    name = st.text_input("Name")
    email = st.text_input("Email")
    st.form_submit_button("Sign up")

Fragments

Define a fragment to rerun independently from the rest of the script.

Python
@st.fragment(run_every="10s")
def fragment():
    df = get_data()
    st.line_chart(df)

Rerun script

Rerun the script immediately.

Python
st.rerun()

Stop execution

Stops execution immediately.

Python
st.stop()

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Pydantic

Auto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.

Python
import streamlit_pydantic as sp

sp.pydantic_form(key="my_form",
  model=ExampleModel)
screenshot

Streamlit Pages

An experimental version of Streamlit Multi-Page Apps. Created by @blackary.

Python
from st_pages import Page, show_pages, add_page_title

show_pages([ Page("streamlit_app.py", "Home", "🏠"),
  Page("other_pages/page2.py", "Page 2", ":books:"), ])

Cache data

Function decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).

Python
@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).

Python
@st.cache_resource
def init_model():
  # Return a global resource here
  return pipeline(
    "sentiment-analysis",
    model="distilbert-base-uncased-finetuned-sst-2-english"
  )

Session state

Session state is a way to share variables between reruns, for each user session.

Python
st.session_state['key'] = value

Query parameters

Get, set, or clear the query parameters that are shown in the browser's URL bar.

Python
st.query_params[key] = value
st.query_params.clear()

Context

st.context provides a read-only interface to access cookies, headers, locale, and other browser-session information.

Python
st.context.cookies
st.context.headers

Setup your connection

screenshot

Create a connection

Connect to a data source or API

Python
conn = st.connection('pets_db', type='sql')
pet_owners = conn.query('select * from pet_owners')
st.dataframe(pet_owners)

Built-in connections

screenshot

SnowflakeConnection

A connection to Snowflake.

Python
conn = st.connection('snowflake')
screenshot

SQLConnection

A connection to a SQL database using SQLAlchemy.

Python
conn = st.connection('sql')

Build your own connections

Connection base class

Build your own connection with BaseConnection.

Python
class MyConnection(BaseConnection[myconn.MyConnection]):
    def _connect(self, **kwargs) -> MyConnection:
        return myconn.connect(**self._secrets, **kwargs)
    def query(self, query):
        return self._instance.query(query)

Secrets management

Secrets singleton

Access secrets from a local TOML file.

Python
key = st.secrets["OpenAI_key"]

Secrets file

Save your secrets in a per-project or per-profile TOML file.

Python
OpenAI_key = "<YOUR_SECRET_KEY>"

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

WS localStorage

A simple synchronous way of accessing localStorage from your app. Created by @gagangoku.

Python
from streamlit_ws_localstorage import injectWebsocketCode

ret = conn.setLocalStorageVal(key='k1', val='v1')
st.write('ret: ' + ret)
screenshot

Streamlit Auth0

The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.

Python
from auth0_component import login_button

user_info = login_button(clientId, domain = domain)
st.write(user_info)

V2 custom components

Register

Register a custom component.

Python
my_component = st.components.v2.component(
    html=HTML,
    js=JS
)
my_component()

Mount

Mount a custom component.

Python
my_component = st.components.v2.component(
    html=HTML,
    js=JS
)
my_component()

npm support code

Support code published through npm.

Terminal
npm i @streamlit/component-v2-lib

Component

Type alias for the component function.

TypeScript
import { Component } from "@streamlit/component-v2-lib";

ComponentArgs

Type alias for the component arguments.

TypeScript
import { ComponentArgs } from "@streamlit/component-v2-lib";

ComponentState

Type alias for the component state.

TypeScript
import { ComponentState } from "@streamlit/component-v2-lib";

OptionalComponentCleanupFunction

Type alias for the component cleanup function.

TypeScript
import { OptionalComponentCleanupFunction } from "@streamlit/component-v2-lib";

V1 custom components

Declare a component

Create and register a custom component.

Python
from st.components.v1 import declare_component
declare_component(
    "custom_slider",
    "/frontend",
)

HTML

Display an HTML string in an iframe.

Python
from st.components.v1 import html
html(
    "<p>Foo bar.</p>"
)

iframe

Load a remote URL in an iframe.

Python
from st.components.v1 import iframe
iframe(
    "docs.streamlit.io"
)

Configuration file

Configures the default settings for your app.

Python
your-project/
├── .streamlit/
│   └── config.toml
└── your_app.py

Get config option

Retrieve a single configuration option.

Python
st.get_option("theme.primaryColor")

Set config option

Set a single configuration option. (This is very limited.)

Python
st.set_option("deprecation.showPyplotGlobalUse", False)

Set page title, favicon, and more

Configures the default settings of the page.

Python
st.set_page_config(
  page_title="My app",
  page_icon=":shark:",
)

st.testing.v1.AppTest

st.testing.v1.AppTest simulates a running Streamlit app for testing.

Python
from streamlit.testing.v1 import AppTest

at = AppTest.from_file("streamlit_app.py")
at.secrets["WORD"] = "Foobar"
at.run()
assert not at.exception

at.text_input("word").input("Bazbat").run()
assert at.warning[0].value == "Try again."

AppTest.from_file

st.testing.v1.AppTest.from_file initializes a simulated app from a file.

Python
from streamlit.testing.v1 import AppTest

at = AppTest.from_file("streamlit_app.py")
at.run()

AppTest.from_string

st.testing.v1.AppTest.from_string initializes a simulated app from a string.

Python
from streamlit.testing.v1 import AppTest

at = AppTest.from_string(app_script_as_string)
at.run()

AppTest.from_function

st.testing.v1.AppTest.from_function initializes a simulated app from a function.

Python
from streamlit.testing.v1 import AppTest

at = AppTest.from_function(app_script_as_callable)
at.run()

Block

A representation of container elements, including:

  • st.chat_message
  • st.columns
  • st.sidebar
  • st.tabs
  • The main body of the app.
Python
# at.sidebar returns a Block
at.sidebar.button[0].click().run()
assert not at.exception

Element

The base class for representation of all elements, including:

  • st.title
  • st.header
  • st.markdown
  • st.dataframe
Python
# at.title returns a sequence of Title
# Title inherits from Element
assert at.title[0].value == "My awesome app"

Button

A representation of st.button and st.form_submit_button.

Python
at.button[0].click().run()

ChatInput

A representation of st.chat_input.

Python
at.chat_input[0].set_value("What is Streamlit?").run()

Checkbox

A representation of st.checkbox.

Python
at.checkbox[0].check().run()

ColorPicker

A representation of st.color_picker.

Python
at.color_picker[0].pick("#FF4B4B").run()

DateInput

A representation of st.date_input.

Python
release_date = datetime.date(2023, 10, 26)
at.date_input[0].set_value(release_date).run()

Multiselect

A representation of st.multiselect.

Python
at.multiselect[0].select("New York").run()

NumberInput

A representation of st.number_input.

Python
at.number_input[0].increment().run()

Radio

A representation of st.radio.

Python
at.radio[0].set_value("New York").run()

SelectSlider

A representation of st.select_slider.

Python
at.select_slider[0].set_range("A","C").run()

Selectbox

A representation of st.selectbox.

Python
at.selectbox[0].select("New York").run()

Slider

A representation of st.slider.

Python
at.slider[0].set_range(2,5).run()

TextArea

A representation of st.text_area.

Python
at.text_area[0].input("Streamlit is awesome!").run()

TextInput

A representation of st.text_input.

Python
at.text_input[0].input("Streamlit").run()

TimeInput

A representation of st.time_input.

Python
at.time_input[0].increment().run()

Toggle

A representation of st.toggle.

Python
at.toggle[0].set_value("True").run()

Third-party components

These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras!

screenshot

Streamlit Ace

Ace editor component for Streamlit. Created by @okld.

Python
from streamlit_ace import st_ace

content = st_ace()
content
screenshot

Streamlit Analytics

Track & visualize user interactions with your streamlit app. Created by @jrieke.

Python
import streamlit_analytics

with streamlit_analytics.track():
    st.text_input("Write something")
forum

Still have questions?

Our forums are full of helpful information and Streamlit experts.