# API reference

Source: https://docs.streamlit.io/develop/api-reference

Streamlit is batteries-included: widgets, charts, data tables, forms, layouts,
navigation, state, caching, sign-in, theming, chat, and testing are built in and
work together, with no separate frontend or API layer. 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.

> **Tip**
>
> Building with a coding agent? Run [`streamlit skills`](https://docs.streamlit.io/develop/api-reference/cli/skills) in your project so your agent uses the current API for your installed version. For details, see [Build with coding agents](https://docs.streamlit.io/develop/concepts/ai-agents/coding-agents).

Browse our API below and click to learn more about any of our available commands! 🎈

## Display almost anything

### Write and magic

**[st.write](https://docs.streamlit.io/develop/api-reference/write-magic/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](https://docs.streamlit.io/develop/api-reference/write-magic/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](https://docs.streamlit.io/develop/api-reference/write-magic/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
```

### Text elements

**[Markdown](https://docs.streamlit.io/develop/api-reference/text/st.markdown)**: Display string formatted as Markdown.

```python
st.markdown("Hello **world**!")
```

**[Title](https://docs.streamlit.io/develop/api-reference/text/st.title)**: Display text in title formatting.

```python
st.title("The app title")
```

**[Header](https://docs.streamlit.io/develop/api-reference/text/st.header)**: Display text in header formatting.

```python
st.header("This is a header")
```

**[Subheader](https://docs.streamlit.io/develop/api-reference/text/st.subheader)**: Display text in subheader formatting.

```python
st.subheader("This is a subheader")
```

**[Badge](https://docs.streamlit.io/develop/api-reference/text/st.badge)**: Display a small, colored badge.

```python
st.badge("New")
```

**[Caption](https://docs.streamlit.io/develop/api-reference/text/st.caption)**: Display text in small font.

```python
st.caption("This is written small caption text")
```

**[Code block](https://docs.streamlit.io/develop/api-reference/text/st.code)**: Display a code block with optional syntax highlighting.

```python
st.code("a = 1234")
```

**[Echo](https://docs.streamlit.io/develop/api-reference/text/st.echo)**: Display some code in the app, then execute it. Useful for tutorials.

```python
with st.echo():
  st.write('This code will be printed')
```

**[LaTeX](https://docs.streamlit.io/develop/api-reference/text/st.latex)**: Display mathematical expressions formatted as LaTeX.

```python
st.latex(r"\int a x^2 \,dx")
```

**[Preformatted text](https://docs.streamlit.io/develop/api-reference/text/st.text)**: Write fixed-width and preformatted text.

```python
st.text("Hello world")
```

**[Divider](https://docs.streamlit.io/develop/api-reference/text/st.divider)**: Display a horizontal rule.

```python
st.divider()
```

**[Get help](https://docs.streamlit.io/develop/api-reference/text/st.help)**: Display object’s doc string, nicely formatted.

```python
st.help(st.write)
st.help(pd.DataFrame)
```

**[Render HTML](https://docs.streamlit.io/develop/api-reference/text/st.html)**: Renders HTML strings to your app.

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

**[Iframe](https://docs.streamlit.io/develop/api-reference/text/st.iframe)**: Display content in an iframe

```python
from pathlib import Path
st.iframe("https://docs.streamlit.io")
st.iframe("<p>Streamlit is cool.</p>")
st.iframe(Path("my_content.html"))
```

### Data elements

**[Dataframes](https://docs.streamlit.io/develop/api-reference/data/st.dataframe)**: Display a dataframe as an interactive table.

```python
st.dataframe(my_data_frame)
```

**[Data editor](https://docs.streamlit.io/develop/api-reference/data/st.data_editor)**: Display a data editor widget.

```python
edited = st.data_editor(df, num_rows="dynamic")
```

**[Column configuration](https://docs.streamlit.io/develop/api-reference/data/st.column_config)**: Configure the display and editing behavior of dataframes and data editors.

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

**[Static tables](https://docs.streamlit.io/develop/api-reference/data/st.table)**: Display a static table.

```python
st.table(my_data_frame)
```

**[Metrics](https://docs.streamlit.io/develop/api-reference/data/st.metric)**: Display a metric in big bold font, with an optional indicator of how the metric changed.

```python
st.metric("My metric", 42, 2)
```

**[Dicts and JSON](https://docs.streamlit.io/develop/api-reference/data/st.json)**: Display object or string as a pretty-printed JSON string.

```python
st.json(my_dict)
```

### Chart elements

**[Simple area charts](https://docs.streamlit.io/develop/api-reference/charts/st.area_chart)**: Display an area chart.

```python
st.area_chart(my_data_frame)
```

**[Simple bar charts](https://docs.streamlit.io/develop/api-reference/charts/st.bar_chart)**: Display a bar chart.

```python
st.bar_chart(my_data_frame)
```

**[Simple line charts](https://docs.streamlit.io/develop/api-reference/charts/st.line_chart)**: Display a line chart.

```python
st.line_chart(my_data_frame)
```

**[Simple scatter charts](https://docs.streamlit.io/develop/api-reference/charts/st.scatter_chart)**: Display a scatter chart.

```python
st.scatter_chart(my_data_frame)
```

**[Scatterplots on maps](https://docs.streamlit.io/develop/api-reference/charts/st.map)**: Display a map with points on it.

```python
st.map(my_data_frame)
```

**[Altair](https://docs.streamlit.io/develop/api-reference/charts/st.altair_chart)**: Display a chart using the Altair library.

```python
st.altair_chart(my_altair_chart)
```

**[ECharts](https://docs.streamlit.io/develop/api-reference/charts/st.echarts_chart)**: Display an interactive Apache ECharts chart, including sankey, gauge, network, and other chart types.

```python
st.echarts_chart(my_echarts_option)
```

**[Vega-Lite](https://docs.streamlit.io/develop/api-reference/charts/st.vega_lite_chart)**: Display a chart using the Vega-Lite library.

```python
st.vega_lite_chart(my_vega_lite_chart)
```

**[Plotly](https://docs.streamlit.io/develop/api-reference/charts/st.plotly_chart)**: Display an interactive Plotly chart.

```python
st.plotly_chart(my_plotly_chart)
```

**[PyDeck](https://docs.streamlit.io/develop/api-reference/charts/st.pydeck_chart)**: Display a chart using the PyDeck library.

```python
st.pydeck_chart(my_pydeck_chart)
```

**[Mermaid chart](https://docs.streamlit.io/develop/api-reference/charts/st.mermaid_chart)**: Display a Mermaid diagram.

```python
st.mermaid_chart("graph LR\n  A --> B")
```

**[GraphViz](https://docs.streamlit.io/develop/api-reference/charts/st.graphviz_chart)**: Display a graph using the dagre-d3 library.

```python
st.graphviz_chart(my_graphviz_spec)
```

**[Matplotlib](https://docs.streamlit.io/develop/api-reference/charts/st.pyplot)**: Display a matplotlib.pyplot figure.

```python
st.pyplot(my_mpl_figure)
```

### Input widgets

**[Button](https://docs.streamlit.io/develop/api-reference/widgets/st.button)**: Display a button widget.

```python
clicked = st.button("Click me")
```

**[Download button](https://docs.streamlit.io/develop/api-reference/widgets/st.download_button)**: Display a download button widget.

```python
st.download_button("Download file", file)
```

**[Form button](https://docs.streamlit.io/develop/api-reference/execution-flow/st.form_submit_button)**: Display a form submit button. For use with `st.form`.

```python
st.form_submit_button("Sign up")
```

**[Link button](https://docs.streamlit.io/develop/api-reference/widgets/st.link_button)**: Display a link button.

```python
st.link_button("Go to gallery", url)
```

**[Menu button](https://docs.streamlit.io/develop/api-reference/widgets/st.menu_button)**: Display a menu button.

```python
st.menu_button("Export", options=["CSV", "JSON", "PDF"])
```

**[Page link](https://docs.streamlit.io/develop/api-reference/widgets/st.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")
```

**[Checkbox](https://docs.streamlit.io/develop/api-reference/widgets/st.checkbox)**: Display a checkbox widget.

```python
selected = st.checkbox("I agree")
```

**[Color picker](https://docs.streamlit.io/develop/api-reference/widgets/st.color_picker)**: Display a color picker widget.

```python
color = st.color_picker("Pick a color")
```

**[Feedback](https://docs.streamlit.io/develop/api-reference/widgets/st.feedback)**: Display a rating or sentiment button group.

```python
st.feedback("stars")
```

**[Multiselect](https://docs.streamlit.io/develop/api-reference/widgets/st.multiselect)**: Display a multiselect widget. The multiselect widget starts as empty.

```python
choices = st.multiselect("Buy", ["milk", "apples", "potatoes"])
```

**[Pills](https://docs.streamlit.io/develop/api-reference/widgets/st.pills)**: Display a pill-button selection widget.

```python
st.pills("Tags", ["Sports", "AI", "Politics"])
```

**[Radio](https://docs.streamlit.io/develop/api-reference/widgets/st.radio)**: Display a radio button widget.

```python
choice = st.radio("Pick one", ["cats", "dogs"])
```

**[Segmented control](https://docs.streamlit.io/develop/api-reference/widgets/st.segmented_control)**: Display a segmented-button selection widget.

```python
st.segmented_control("Filter", ["Open", "Closed", "All"])
```

**[Selectbox](https://docs.streamlit.io/develop/api-reference/widgets/st.selectbox)**: Display a select widget.

```python
choice = st.selectbox("Pick one", ["cats", "dogs"])
```

**[Select-slider](https://docs.streamlit.io/develop/api-reference/widgets/st.select_slider)**: Display a slider widget to select items from a list.

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

**[Toggle](https://docs.streamlit.io/develop/api-reference/widgets/st.toggle)**: Display a toggle widget.

```python
activated = st.toggle("Activate")
```

**[Number input](https://docs.streamlit.io/develop/api-reference/widgets/st.number_input)**: Display a numeric input widget.

```python
choice = st.number_input("Pick a number", 0, 10)
```

**[Slider](https://docs.streamlit.io/develop/api-reference/widgets/st.slider)**: Display a slider widget.

```python
number = st.slider("Pick a number", 0, 100)
```

**[Date input](https://docs.streamlit.io/develop/api-reference/widgets/st.date_input)**: Display a date input widget.

```python
date = st.date_input("Your birthday")
```

**[Datetime input](https://docs.streamlit.io/develop/api-reference/widgets/st.datetime_input)**: Display a datetime input widget.

```python
datetime = st.datetime_input("Schedule your event")
```

**[Time input](https://docs.streamlit.io/develop/api-reference/widgets/st.time_input)**: Display a time input widget.

```python
time = st.time_input("Meeting time")
```

**[Chat input](https://docs.streamlit.io/develop/api-reference/chat/st.chat_input)**: Display a chat input widget.

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

**[Text-area](https://docs.streamlit.io/develop/api-reference/widgets/st.text_area)**: Display a multi-line text input widget.

```python
text = st.text_area("Text to translate")
```

**[Text input](https://docs.streamlit.io/develop/api-reference/widgets/st.text_input)**: Display a single-line text input widget.

```python
name = st.text_input("First name")
```

**[Pagination](https://docs.streamlit.io/develop/api-reference/widgets/st.pagination)**: Display a pagination widget.

```python
page = st.pagination(10)
```

**[Audio input](https://docs.streamlit.io/develop/api-reference/widgets/st.audio_input)**: Display a widget that allows users to record with their microphone.

```python
speech = st.audio_input("Record a voice message")
```

**[Data editor](https://docs.streamlit.io/develop/api-reference/data/st.data_editor)**: Display a data editor widget.

```python
edited = st.data_editor(df, num_rows="dynamic")
```

**[File uploader](https://docs.streamlit.io/develop/api-reference/widgets/st.file_uploader)**: Display a file uploader widget.

```python
data = st.file_uploader("Upload a CSV")
```

**[Camera input](https://docs.streamlit.io/develop/api-reference/widgets/st.camera_input)**: Display a widget that allows users to upload images directly from a camera.

```python
image = st.camera_input("Take a picture")
```

### Media elements

**[Image](https://docs.streamlit.io/develop/api-reference/media/st.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")
```

**[Logo](https://docs.streamlit.io/develop/api-reference/media/st.logo)**: Display a logo in the upper-left corner of your app and its sidebar.

```python
st.logo("logo.jpg")
```

**[PDF](https://docs.streamlit.io/develop/api-reference/media/st.pdf)**: Display a PDF file.

```python
st.pdf("my_document.pdf")
```

**[Audio](https://docs.streamlit.io/develop/api-reference/media/st.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")
```

**[Video](https://docs.streamlit.io/develop/api-reference/media/st.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")
```

### Layouts and containers

**[Columns](https://docs.streamlit.io/develop/api-reference/layout/st.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")
```

**[Container](https://docs.streamlit.io/develop/api-reference/layout/st.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")
```

**[Modal dialog](https://docs.streamlit.io/develop/api-reference/execution-flow/st.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", type="email")
```

**[Empty](https://docs.streamlit.io/develop/api-reference/layout/st.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")
```

**[Expander](https://docs.streamlit.io/develop/api-reference/layout/st.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")
```

**[Grid](https://docs.streamlit.io/develop/api-reference/layout/st.grid)**: Insert a responsive grid of cells that reflow with the available width.

```python
grid = st.grid(3)
grid.metric("Revenue", "$1.2M", "+8%")
grid.metric("Pipeline", "$4.8M", "+12%")
grid.metric("Retention", "96%", "-0.4%")
```

**[Popover](https://docs.streamlit.io/develop/api-reference/layout/st.popover)**: Insert a multi-element popover container that can be opened/closed.

```python
with st.popover("Settings"):
  st.checkbox("Show completed")
```

**[Sidebar](https://docs.streamlit.io/develop/api-reference/layout/st.sidebar)**: Display items in a sidebar.

```python
st.sidebar.write("This lives in the sidebar")
st.sidebar.button("Click me!")
```

**[Bottom](https://docs.streamlit.io/develop/api-reference/layout/st.bottom)**: Display items at the bottom of the window.

```python
st.bottom.chat_input("Say something")
```

**[Space](https://docs.streamlit.io/develop/api-reference/layout/st.space)**: Add vertical or horizontal space.

```python
st.space("small")
```

**[Tabs](https://docs.streamlit.io/develop/api-reference/layout/st.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")
```

### 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 input](https://docs.streamlit.io/develop/api-reference/chat/st.chat_input)**: Display a chat input widget.

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

**[Chat message](https://docs.streamlit.io/develop/api-reference/chat/st.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))
```

**[Status container](https://docs.streamlit.io/develop/api-reference/status/st.status)**: Display output of long-running tasks in a container.

```python
with st.status('Running'):
  do_something_slow()
```

**[st.write_stream](https://docs.streamlit.io/develop/api-reference/write-magic/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)
```

### Status elements

**[Progress bar](https://docs.streamlit.io/develop/api-reference/status/st.progress)**: Display a progress bar.

```python
for i in range(101):
  st.progress(i)
  do_something_slow()
```

**[Spinner](https://docs.streamlit.io/develop/api-reference/status/st.spinner)**: Temporarily displays a message while executing a block of code.

```python
with st.spinner("Please wait..."):
  do_something_slow()
```

**[Status container](https://docs.streamlit.io/develop/api-reference/status/st.status)**: Display output of long-running tasks in a container.

```python
with st.status('Running'):
  do_something_slow()
```

**[Skeleton](https://docs.streamlit.io/develop/api-reference/status/st.skeleton)**: Display a skeleton placeholder while loading.

```python
with st.skeleton(height=200):
  do_something_slow()
```

**[Toast](https://docs.streamlit.io/develop/api-reference/status/st.toast)**: Briefly displays a toast message in the top-right corner.

```python
st.toast('Butter!', icon='🧈')
```

**[Balloons](https://docs.streamlit.io/develop/api-reference/status/st.balloons)**: Display celebratory balloons!

```python
do_something()

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

**[Snowflakes](https://docs.streamlit.io/develop/api-reference/status/st.snow)**: Display celebratory snowflakes!

```python
do_something()

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

**[Success box](https://docs.streamlit.io/develop/api-reference/status/st.success)**: Display a success message.

```python
st.success("Match found!")
```

**[Info box](https://docs.streamlit.io/develop/api-reference/status/st.info)**: Display an informational message.

```python
st.info("Dataset is updated every day at midnight.")
```

**[Warning box](https://docs.streamlit.io/develop/api-reference/status/st.warning)**: Display warning message.

```python
st.warning("Unable to fetch image. Skipping...")
```

**[Error box](https://docs.streamlit.io/develop/api-reference/status/st.error)**: Display error message.

```python
st.error("We encountered an error")
```

**[Exception output](https://docs.streamlit.io/develop/api-reference/status/st.exception)**: Display an exception.

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

**[Streamlit Extras](https://extras.streamlit.app/)**: A library with useful Streamlit extras. Created by [@arnaudmiribel](https://github.com/arnaudmiribel/).

```python
from streamlit_extras.three_viewer import three_viewer

three_viewer("https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/glTF-Binary/Duck.glb", height=400)

```

**[Streamlit Aggrid](https://github.com/PablocFonseca/streamlit-aggrid)**: Implementation of Ag-Grid component for Streamlit. Created by [@PablocFonseca](https://github.com/PablocFonseca).

```python
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
grid_return = AgGrid(df, editable=True)

new_df = grid_return['data']
```

**[Streamlit Folium](https://github.com/randyzwitch/streamlit-folium)**: Streamlit Component for rendering Folium maps. Created by [@randyzwitch](https://github.com/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)
```

**[Authenticator](https://github.com/mkhorasani/Streamlit-Authenticator)**: A secure authentication module to validate user credentials. Created by [@mkhorasani](https://github.com/mkhorasani).

```python
import streamlit_authenticator as stauth

authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'],
config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized'])
```

**[Streamlit Ace](https://github.com/okld/streamlit-ace)**: Ace editor component for Streamlit. Created by [@okld](https://github.com/okld).

```python
from streamlit_ace import st_ace

content = st_ace()
content
```

**[Streamlit Webrtc](https://github.com/whitphx/streamlit-webrtc)**: Handling and transmitting real-time video/audio streams with Streamlit. Created by [@whitphx](https://github.com/whitphx).

```python
from streamlit_webrtc import webrtc_streamer

webrtc_streamer(key="sample")

```

**[Streamlit Elements](https://github.com/okld/streamlit-elements)**: Create a draggable and resizable dashboard in Streamlit. Created by [@okls](https://github.com/okls).

```python
from streamlit_elements import elements, mui, html

with elements("new_element"):
  mui.Typography("Hello world")
```

**[Streamlit Agraph](https://github.com/ChrisDelClea/streamlit-agraph)**: A Streamlit Graph Vis, based on [react-graph-vis](https://github.com/crubier/react-graph-vis). Created by [@ChrisDelClea](https://github.com/ChrisDelClea).

```python
from streamlit_agraph import agraph, Node, Edge, Config

agraph(nodes=nodes, edges=edges, config=config)

```

**[Autorefresh](https://github.com/kmcgrady/streamlit-autorefresh)**: Force a refresh without tying up a script. Created by [@kmcgrady](https://github.com/kmcgrady).

```python
from streamlit_autorefresh import st_autorefresh

st_autorefresh(interval=2000, limit=100,
  key="fizzbuzzcounter")
```

**[Streamlit Pydantic](https://github.com/lukasmasuch/streamlit-pydantic)**: Auto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by [@lukasmasuch](https://github.com/lukasmasuch).

```python
import streamlit_pydantic as sp

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

**[Drawable Canvas](https://github.com/andfanilo/streamlit-drawable-canvas)**: Provides a sketching canvas using [Fabric.js](http://fabricjs.com/). Created by [@andfanilo](https://github.com/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, height=150, key="canvas")
```

**[Streamlit Cropper](https://github.com/turner-anderson/streamlit-cropper)**: A simple image cropper for Streamlit. Created by [@turner-anderson](https://github.com/turner-anderson).

```python
from streamlit_cropper import st_cropper

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

```

**[Image Coordinates](https://github.com/blackary/streamlit-image-coordinates)**: Get the coordinates of clicks on an image. Created by [@blackary](https://github.com/blackary/).

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

st.write(value)
```

**[Streamlit Lottie](https://github.com/andfanilo/streamlit-lottie)**: Integrate [Lottie](https://lottiefiles.com/) animations inside your Streamlit app. Created by [@andfanilo](https://github.com/andfanilo).

```python
lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json")

st_lottie(lottie_hello, key="hello")

```

**[Image Comparison](https://github.com/fcakyon/streamlit-image-comparison)**: Compare images with a slider using [JuxtaposeJS](https://juxtapose.knightlab.com/). Created by [@fcakyon](https://github.com/fcakyon).

```python
from streamlit_image_comparison import image_comparison

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

```

**[Camera input live](https://github.com/blackary/streamlit-camera-input-live)**: Alternative for st.camera_input which returns the webcam images live. Created by [@blackary](https://github.com/blackary).

```python
from camera_input_live import camera_input_live

image = camera_input_live()
st.image(image)
```

**[Stqdm](https://github.com/Wirg/stqdm)**: The simplest way to handle a progress bar in streamlit app. Created by [@Wirg](https://github.com/Wirg).

```python
from time import sleep
from stqdm import stqdm
for _ in stqdm(range(50)):
    sleep(0.5)
```

## App logic and configuration

### App server

**[App](https://docs.streamlit.io/develop/api-reference/server/st.app)**: Configure the underlying Starlette server for your app.

```python
app = st.App("streamlit_app.py")
```

### Authentication

**[Log in a user](https://docs.streamlit.io/develop/api-reference/user/st.login)**

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

```python
st.login()
```

**[Log out a user](https://docs.streamlit.io/develop/api-reference/user/st.logout)**

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

```python
st.logout()
```

**[User info](https://docs.streamlit.io/develop/api-reference/user/st.user)**

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

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

### Navigation and pages

**[Navigation](https://docs.streamlit.io/develop/api-reference/navigation/st.navigation)**: Configure the available pages in a multipage app.

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

**[Page](https://docs.streamlit.io/develop/api-reference/navigation/st.page)**: Define a page in a multipage app.

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

**[Page link](https://docs.streamlit.io/develop/api-reference/widgets/st.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](https://docs.streamlit.io/develop/api-reference/navigation/st.switch_page)**: Programmatically navigates to a specified page.

```python
st.switch_page("pages/my_page.py")
```

### Execution flow

**[Modal dialog](https://docs.streamlit.io/develop/api-reference/execution-flow/st.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", type="email")
```

**[Forms](https://docs.streamlit.io/develop/api-reference/execution-flow/st.form)**: 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", type="email")
    st.form_submit_button("Sign up")
```

**[Fragments](https://docs.streamlit.io/develop/api-reference/execution-flow/st.fragment)**: 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](https://docs.streamlit.io/develop/api-reference/execution-flow/st.rerun)**: Rerun the script immediately.

```python
st.rerun()
```

**[Stop execution](https://docs.streamlit.io/develop/api-reference/execution-flow/st.stop)**: Stops execution immediately.

```python
st.stop()
```

### Caching and state

**[Cache data](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.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](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.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](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.session_state)**: Session state is a way to share variables between reruns, for each user session.

```python
st.session_state['key'] = value
```

**[Query parameters](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.query_params)**: 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](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.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
```

### Connections and databases

#### Setup your connection

**[Create a connection](https://docs.streamlit.io/develop/api-reference/connections/st.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

**[SnowflakeConnection](https://docs.streamlit.io/develop/api-reference/connections/st.connections.snowflakeconnection)**: A connection to Snowflake.

```python
conn = st.connection('snowflake')
```

**[SQLConnection](https://docs.streamlit.io/develop/api-reference/connections/st.connections.sqlconnection)**: A connection to a SQL database using SQLAlchemy.

```python
conn = st.connection('sql')
```

#### Build your own connections

**[Connection base class](https://docs.streamlit.io/develop/api-reference/connections/st.connections.baseconnection)**: 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](https://docs.streamlit.io/develop/api-reference/connections/st.secrets)**: Access secrets from a local TOML file.

```python
key = st.secrets["OpenAI_key"]
```

**[Secrets file](https://docs.streamlit.io/develop/api-reference/connections/secrets.toml)**: Save your secrets in a per-project or per-profile TOML file.

```python
OpenAI_key = "<YOUR_SECRET_KEY>"
```

### Custom Components

#### V2 custom components

**[Register](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v2.component)**: Register a custom component.

```python
my_component = st.components.v2.component(
    "my_component",
    html=HTML,
    js=JS
)
my_component()
```

**[Mount](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v2.types.componentrenderer)**: Mount a custom component.

```python
my_component = st.components.v2.component(
    "my_component",
    html=HTML,
    js=JS
)
my_component()
```

**[npm support code](https://docs.streamlit.io/develop/api-reference/custom-components/component-v2-lib)**: Support code published through npm.

```bash
npm i @streamlit/component-v2-lib
```

**[FrontendRenderer](https://docs.streamlit.io/develop/api-reference/custom-components/component-v2-lib-frontendrenderer)**: Type alias for the component function.

```typescript
import { FrontendRenderer } from "@streamlit/component-v2-lib";
```

**[FrontendRendererArgs](https://docs.streamlit.io/develop/api-reference/custom-components/component-v2-lib-frontendrendererargs)**: Type alias for the component arguments.

```typescript
import { FrontendRendererArgs } from "@streamlit/component-v2-lib";
```

**[FrontendState](https://docs.streamlit.io/develop/api-reference/custom-components/component-v2-lib-frontendstate)**: Type alias for the component state.

```typescript
import { FrontendState } from "@streamlit/component-v2-lib";
```

**[CleanupFunction](https://docs.streamlit.io/develop/api-reference/custom-components/component-v2-lib-cleanupfunction)**: Type alias for the component cleanup function.

```typescript
import { CleanupFunction } from "@streamlit/component-v2-lib";
```

#### V1 custom components

**[Declare a component](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.declare_component)**: Create and register a custom component.

```python
from streamlit.components.v1 import declare_component
declare_component(
    "custom_slider",
    "/frontend",
)
```

**[HTML](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.html)**

> This command was deprecated in version 1.56.0. Use `st.iframe` instead, or `st.html` to insert HTML without an iframe.

Display an HTML string in an iframe.

```python
from streamlit.components.v1 import html
html(
    "<p>Foo bar.</p>"
)
```

**[iframe](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.iframe)**

> This command was deprecated in version 1.56.0. Use `st.iframe` instead.

Load a remote URL in an iframe.

```python
from streamlit.components.v1 import iframe
iframe(
    "https://docs.streamlit.io"
)
```

### Configuration

**[Configuration file](https://docs.streamlit.io/develop/api-reference/configuration/config.toml)**: Configures the default settings for your app.

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

**[Get config option](https://docs.streamlit.io/develop/api-reference/configuration/st.get_option)**: Retrieve a single configuration option.

```python
st.get_option("theme.primaryColor")
```

**[Set config option](https://docs.streamlit.io/develop/api-reference/configuration/st.set_option)**: Set a single configuration option. (This is very limited.)

```python
st.set_option("client.showErrorDetails", "none")
```

**[Set page title, favicon, and more](https://docs.streamlit.io/develop/api-reference/configuration/st.set_page_config)**: Configures the default settings of the page.

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

## Developer tools

### App testing

**[st.testing.v1.AppTest](https://docs.streamlit.io/develop/api-reference/app-testing/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](https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestfrom_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](https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestfrom_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](https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestfrom_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](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeblock)**: 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](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeelement)**: 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](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treebutton)**: A representation of `st.button` and `st.form_submit_button`.

```python
at.button[0].click().run()
```

**[ChatInput](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treechatinput)**: A representation of `st.chat_input`.

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

**[Checkbox](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treecheckbox)**: A representation of `st.checkbox`.

```python
at.checkbox[0].check().run()
```

**[ColorPicker](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treecolorpicker)**: A representation of `st.color_picker`.

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

**[DateInput](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treedateinput)**: A representation of `st.date_input`.

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

**[Multiselect](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treemultiselect)**: A representation of `st.multiselect`.

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

**[NumberInput](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treenumberinput)**: A representation of `st.number_input`.

```python
at.number_input[0].increment().run()
```

**[Radio](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeradio)**: A representation of `st.radio`.

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

**[SelectSlider](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeselectslider)**: A representation of `st.select_slider`.

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

**[Selectbox](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeselectbox)**: A representation of `st.selectbox`.

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

**[Slider](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeslider)**: A representation of `st.slider`.

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

**[TextArea](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treetextarea)**: A representation of `st.text_area`.

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

**[TextInput](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treetextinput)**: A representation of `st.text_input`.

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

**[TimeInput](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treetimeinput)**: A representation of `st.time_input`.

```python
at.time_input[0].increment().run()
```

**[Toggle](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treetoggle)**: A representation of `st.toggle`.

```python
at.toggle[0].set_value(True).run()
```
