st.query_params is Streamlit’s dictionary-like interface for reading and updating the key-value pairs in an app’s URL query string. It enables deep links: a URL can preserve widget selections so users can reopen or share a specific dashboard view. section 7.6.1 section 7.8
Use the interface to keep URL state and widget state synchronized:
- Read a value with st.query_params.get("key") or st.query_params["key"]. section 7.6.1 section 7.6.3
- Set a value directly, such as st.query_params["pie_chart_dimension"] = "Gender", to update the browser URL. section 7.6.1
- Load URL values into widgets once, using st.session_state so later reruns do not overwrite user changes. section 7.6.3
- Write changed widget values back with st.query_params.from_dict(), limiting the exported keys to those prefixed with w:. section 7.6.3
A shareable dashboard view
A URL such as start_date=2024-08-01&end_date=2024-08-31&product_name=RoyalQuill can populate date and filter widgets when the app loads. Widget keys such as w:start, w:end, and w:filter|Product name identify the values that should travel in the URL. Dates and lists need explicit encoding and decoding: dates use D# followed by ISO format, while lists use L# followed by comma-separated values. section 7.6.1 section 7.6.3
Listing 7.2 Getting and setting query params
import streamlit as st
def get_param(key):
return st.query_params.get(key, None)
def set_widget_defaults():
for key in st.query_params:
if key.startswith('w:') and key not in st.session_state:
st.session_state[key] = get_param(key)
def set_params():
query_params_dict = {}
for key in st.session_state:
if key.startswith('w:'):
value = st.session_state[key]
query_params_dict[key] = value
st.query_params.from_dict(query_params_dict)
Browse the compact helper functions for reading parameters, initializing widget defaults, and writing selected widget state back to the URL. section 7.6.3
