liveBook · Manning

St.query_params

As explained in Build Python Web Apps with Streamlit

st.query_params is Streamlit's dictionary-like interface for reading and updating the query parameters in an app's URL.

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

How Build Python Web Apps with Streamlit covers it

How deep it goes
Explains dictionary access, session-state synchronization, widget-key filtering, and serialization, including a date-input type error.
Examples
Uses dashboard dates, product filters, chart dimensions, comparison choices, and serialized list and date values.
What you can do after
Build it from scratch to create shareable URLs that restore and track Streamlit widget selections.
How it connects
Connects URL query parameters with st.session_state, Streamlit widgets, and deep links.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.