Skip to content

Latest commit

 

History

History
2426 lines (1880 loc) · 83 KB

api-reference.md

File metadata and controls

2426 lines (1880 loc) · 83 KB

API reference

Generated by tools/gen_api_docs.py from the source doc comments — do not edit by hand.

All element and widget methods are called on St (the st passed to your app function) or on a container returned by it (st.sidebar, st.columns(2)[0], st.expander("..."), ...). Optional parameters are usually passed by name: st.slider("x", 0, 10, 5, step: 2, key: "s").

Contents

Text & status elements

Source: source/streamlitd/elements.d

Methods on St for text, alerts, metrics and progress.

final class ProgressBar

Handle returned by st.progress; call .progress(...) to update it.

void progress(int value, string text = null)

Update the bar (0..100).

void progress(double value, string text = null)

Update the bar (0.0..1.0).

struct Spinner

RAII spinner returned by st.spinner(text); removed when it goes out of scope.

struct LegendItem

An entry of st.legend.

struct FeedItem

An item of st.feed (a notification or alert).

struct TimelineItem

An event of st.timeline.

void title(string text, string anchor = null, string help = null)

st.title

void header(string text, string anchor = null, string help = null, string divider = null)

st.header

void subheader(string text, string anchor = null, string help = null, string divider = null)

st.subheader

void markdown(string body_, bool unsafeAllowHtml = false, string help = null)

st.markdown — GitHub-flavoured Markdown. Raw HTML is escaped unless unsafeAllowHtml. Colours as in Streamlit: :red[text], :blue-background[text], :green-badge[text] (a small label, like st.badge).

void caption(string body_, bool unsafeAllowHtml = false)

st.caption

void text(string body_, string help = null)

st.text — fixed-width preformatted text.

void code(string body_, string language = "d", bool lineNumbers = false)

st.code

void latex(string body_, string help = null)

st.latex — renders a LaTeX expression with KaTeX (bundled). Markdown also supports $inline$ and $$display$$ math.

void html(string body_)

st.html — raw HTML (trusted).

void linkButton(string label, string url, string help = null, string type = "secondary", string icon = null, bool disabled = false, bool useContainerWidth = false)

st.link_button: a button that opens a URL.

void badge(string label, string icon = null, string color = "blue")

st.badge: a small colored label. Colors: blue, green, orange, red, violet, gray, primary. Inside Markdown text, write :blue-badge[label].

void divider()

st.divider

void success(string body_, string icon = null)

st.success

void info(string body_, string icon = null)

st.info

void warning(string body_, string icon = null)

st.warning

void error(string body_, string icon = null)

st.error

void banner(string body_, string type = "info", bool dismissible = true, string key = null, string icon = null)

A notice across the top of the page, above the main content (streamlitd only), e.g. planned maintenance or "STAGING". type: "info", "success", "warning" or "error" (Markdown body). With dismissible, the viewer can close it; it then stays closed in that browser tab until its text changes, or, with a key, until the key changes (so fixing a typo does not show it again). Call it once per run, like other elements.

void avatar(string name, string image = null, string size = "medium")

A round picture or the initials of name (streamlitd only). size: "small", "medium" or "large".

void details(string[2][] rows, bool inline = false)

Labels and values of one record, in a two-column list (streamlitd only), e.g. a customer's details. Values are Markdown. inline: true puts them side by side in one row (a stat strip).

void details(Json record, bool inline = false)

ditto, from a JSON object: its keys are the labels, in alphabetical order (JSON objects keep no order; use the string[2][] form for your own order). Non-string values are shown as JSON.

void stepper(string[] steps, size_t current, string orientation = "horizontal")

Progress through a sequence of steps (streamlitd only), e.g. a multi-step form. current is the index of the current step (0-based); steps before it are shown as done, and current == steps.length shows all as done. orientation: "horizontal" or "vertical".

void skeleton(int lines = 3, int height = 0)

A placeholder that shows content is loading (streamlitd only): lines text lines, or a block of height pixels. Typical use: auto ph = st.empty(); ph.skeleton(); ...; ph.dataframe(df);.

void timeline(TimelineItem[] items)

A vertical list of events (streamlitd only), newest or oldest first as given.

void rerunButton(string label = "Rerun", string icon = "⟳", string help = null)

A button that reruns the whole app, like ⟳ in the header (streamlitd only). Place it anywhere, e.g. st.sidebar.rerunButton() with [ui] rerunButton = "hidden".

void settingsButton(string label = "Appearance", string icon = "⚙", string help = null)

A button that opens the viewer's appearance panel (mode, design style, color scheme) next to it, like ⚙ in the header (streamlitd only). It shows nothing while the app does not let viewers change the appearance ([theme] allowSwitch = false).

void exception(Throwable e)

st.exception

void metric(string label, string value, string delta = null, string deltaColor = "normal", string help = null, bool border = false, double[] chartData = null, string chartType = "line", string caption = null)

st.metric. delta starting with "-" is shown as a decrease. chartData draws a small trend chart under the value (chartType: "line", "bar" or "area"); caption adds a small line, e.g. "was 1,204 on 01.10" (streamlitd only).

void metric(string label, int value, string delta = null, string deltaColor = "normal", string help = null, bool border = false, double[] chartData = null, string chartType = "line", string caption = null)

ditto (an exact int overload, so int values are not ambiguous between long and double)

void metric(string label, long value, string delta = null, string deltaColor = "normal", string help = null, bool border = false, double[] chartData = null, string chartType = "line", string caption = null)

ditto

void metric(string label, double value, string delta = null, string deltaColor = "normal", string help = null, bool border = false, double[] chartData = null, string chartType = "line", string caption = null)

ditto

void emptyState(string title, string body_ = null, string icon = "🗂️")

A placeholder for "nothing here yet" (streamlitd only): an icon, a title and a Markdown body, e.g. when a filter matches no rows.

void legend(LegendItem[] items, string title = null)

A legend for charts and colour-coded tables (streamlitd only).

void proportionBar(double[] values, string[] labels, string[] colors = null, string format = null)

A bar split into parts in proportion to values, with a legend (streamlitd only), e.g. the share of stock per status. colors: tokens ("success", "warning", "error", "info", "muted", "primary") or hex colours; default: the chart palette.

void feed(FeedItem[] items)

A list of notifications or alerts (streamlitd only): each with a title, a Markdown body, a time, a severity colour, an unread dot and small badges.

void json(Json value, bool expanded = true)

st.json — a collapsible JSON viewer.

void json(string jsonText, bool expanded = true)

ditto, from JSON text (shown as a string if it does not parse).

void jsonOf(T)(T value, bool expanded = true)

st.json for any D value (struct, class, array, associative array ...), serialized to JSON. Use jsonOf!T(value, expanded: false) when passing named arguments.

ProgressBar progress(int value, string text = null)

st.progress — value in 0..100; returns a handle that can be updated.

ProgressBar progress(double value, string text = null)

st.progress — value in 0.0..1.0.

Spinner spinner(string text = "In progress...")

st.spinner — keep the returned value alive while working: { auto s = st.spinner("Loading..."); work(); }

void spinner(string text, scope void delegate() body_)

st.spinner with a body.

void write(Args...)(Args args)

st.write — renders each argument depending on its type.

Input widgets

Source: source/streamlitd/widgets.d

Widgets return their current value. Pass key: to bind the value to st.session[key].

struct TreeNode

A node of st.treeSelect.

struct DateRange

A date range from st.dateRangeInput (start <= end, both included).

bool button(string label, string key = null, string help = null, void delegate() onClick = null, bool disabled = false, string type = "secondary", bool useContainerWidth = false, string icon = null)

st.button — true only on the run triggered by the click.

string menuButton(string label, string[] items, string icon = null, string type = "secondary", string key = null, string help = null, bool disabled = false, void delegate() onClick = null)

A button that opens a menu of actions (streamlitd only). Returns the item picked in this run, otherwise null, like button. An item "-" is a separator. switch (st.menuButton("Export", ["CSV", "Excel", "-", "Print"])) { case "CSV": ...; default: }

size_t pagination(size_t totalItems, size_t pageSize = 10, string key = null, void delegate() onChange = null, bool disabled = false, string label = "Pages")

Page buttons (‹ 1 2 … 9 ›) for long tables and lists (streamlitd only). Returns the selected page, starting at 1; it stays within the pages when totalItems shrinks. auto page = st.pagination(rows.length, 20); st.table(rows[(page - 1) * 20 .. min(page * 20, rows.length)]);

bool formSubmitButton(string label = "Submit", string help = null, void delegate() onClick = null, string type = "secondary", bool disabled = false, bool useContainerWidth = false, string icon = null)

st.form_submit_button — must be called inside st.form.

bool checkbox(string label, bool value = false, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.checkbox

bool toggle(string label, bool value = false, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.toggle

string radio(string label, string[] options, size_t index = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, bool horizontal = false, string labelVisibility = "visible", string[] captions = null)

st.radio

T radioOf(T)(string label, T[] options, size_t index = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, bool horizontal = false, string delegate(T) formatFunc = null, string labelVisibility = "visible", string[] captions = null)

st.radio over any option type (use radioOf!T(...) when passing named arguments).

string selectbox(string label, string[] options, ptrdiff_t index = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string placeholder = "Choose an option", string labelVisibility = "visible")

st.selectbox. Pass index = -1 to start with no selection (returns null).

T selectboxOf(T)(string label, T[] options, ptrdiff_t index = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string placeholder = "Choose an option", string delegate(T) formatFunc = null, string labelVisibility = "visible")

st.selectbox over any option type (returns T.init when nothing is selected).

string selectSlider(string label, string[] options, size_t index = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.select_slider

T selectSliderOf(T)(string label, T[] options, size_t index = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string delegate(T) formatFunc = null, string labelVisibility = "visible")

st.select_slider over any option type.

string[] multiselect(string label, string[] options, string[] default_ = null, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, size_t maxSelections = 0, string placeholder = "Choose options", string labelVisibility = "visible")

st.multiselect

T[] multiselectOf(T)(string label, T[] options, T[] default_ = null, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, size_t maxSelections = 0, string placeholder = "Choose options", string delegate(T) formatFunc = null, string labelVisibility = "visible")

st.multiselect over any option type.

int slider(string label, int minValue, int maxValue, int value, int step = 1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string labelVisibility = "visible")

st.slider (int)

long slider(string label, long minValue, long maxValue, long value, long step = 1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string labelVisibility = "visible")

st.slider (long)

double slider(string label, double minValue, double maxValue, double value, double step = 0.01, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string labelVisibility = "visible")

st.slider (double)

int[2] slider(string label, int minValue, int maxValue, int[2] value, int step = 1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string labelVisibility = "visible")

st.slider with an int range [low, high].

double[2] slider(string label, double minValue, double maxValue, double[2] value, double step = 0.01, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string labelVisibility = "visible")

st.slider with a double range [low, high].

double numberInput(string label, double value = 0, double minValue = -double.infinity, double maxValue = double.infinity, double step = 0.01, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string placeholder = null, string labelVisibility = "visible")

st.number_input (double)

int numberInput(string label, int value, double minValue = -double.infinity, double maxValue = double.infinity, int step = 1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string format = null, string placeholder = null, string labelVisibility = "visible")

st.number_input (int) — chosen when value is an int.

string textInput(string label, string value = "", size_t maxChars = 0, string key = null, string type = "default", string help = null, void delegate() onChange = null, string placeholder = null, bool disabled = false, string labelVisibility = "visible")

st.text_input. type may be "default" or "password".

string textArea(string label, string value = "", int height = 0, size_t maxChars = 0, string key = null, string help = null, void delegate() onChange = null, string placeholder = null, bool disabled = false, string labelVisibility = "visible")

st.text_area

Date dateInput(string label, Date value = Date.init, Date minValue = Date.init, Date maxValue = Date.init, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.date_input (defaults to today).

DateRange dateRangeInput(string label, DateRange value = DateRange.init, Date minValue = Date.init, Date maxValue = Date.init, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

A date range: two clicks in the calendar (or typing "2026-01-01 – 2026-01-31") pick the start and the end (Streamlit: st.date_input with a pair). Defaults to today–today; the result always has start <= end and stays within minValue/maxValue.

string[] tagsInput(string label, string[] value = null, string[] suggestions = null, size_t maxTags = 0, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string placeholder = null, string labelVisibility = "visible")

Free-text tags (streamlitd only): typed text becomes a chip on Enter or comma; suggestions are offered while typing. Tags are trimmed, empty and repeated ones dropped, and at most maxTags kept (0 = no limit).

string[] treeSelect(string label, TreeNode[] nodes, string[] value = null, bool multi = true, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string placeholder = null, string labelVisibility = "visible")

Pick nodes of a tree in a searchable pop-up (streamlitd only). Returns the ids of the picked nodes in tree order. With multi, checking a node checks its whole subtree (also a parent id in value), and a node is included when all of its children are; without it, one node. Ids that are not in the tree are dropped.

void copyButton(string text, string label = "Copy", string icon = "📋", string help = null, bool url = false)

A button that copies text to the clipboard (streamlitd only); it does not rerun the app. With url, a path such as "/auth/reset?token=..." is copied as a full URL of this app (the browser adds the address it is on).

TimeOfDay timeInput(string label, TimeOfDay value = TimeOfDay.init, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, int stepSeconds = 900, string labelVisibility = "visible")

st.time_input

string colorPicker(string label, string value = "#000000", string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.color_picker

string pills(string label, string[] options, ptrdiff_t index = -1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible", bool required = false)

st.pills (single selection). Returns null when nothing is selected. With required, one option is always selected (the first, unless index says otherwise) and clicking the selected one keeps it (streamlitd only).

T pillsOf(T)(string label, T[] options, ptrdiff_t index = -1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string delegate(T) formatFunc = null, string labelVisibility = "visible")

st.pills over any option type (returns T.init when nothing is selected).

string[] pillsMulti(string label, string[] options, string[] default_ = null, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.pills(selection_mode="multi")

string segmentedControl(string label, string[] options, ptrdiff_t index = -1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible", bool required = false)

st.segmented_control (single selection). Returns null when nothing is selected. With required, one option is always selected, like a tab bar (streamlitd only).

T segmentedControlOf(T)(string label, T[] options, ptrdiff_t index = -1, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string delegate(T) formatFunc = null, string labelVisibility = "visible")

st.segmented_control over any option type (returns T.init when nothing is selected).

string[] segmentedControlMulti(string label, string[] options, string[] default_ = null, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.segmented_control(selection_mode="multi")

ptrdiff_t feedback(string type = "thumbs", string key = null, void delegate() onChange = null, bool disabled = false)

st.feedback: "thumbs" (0 = down, 1 = up), "faces" (0..4) or "stars" (0..4). Returns -1 when nothing is selected.

string chatInput(string placeholder = "Your message", string key = null, size_t maxChars = 0, bool disabled = false, void delegate() onSubmit = null)

st.chat_input — returns the submitted message, or null if nothing was submitted this run. When called on the main area it is pinned to the bottom of the page.

Layout containers

Source: source/streamlitd/layout.d

Containers return a new St that writes into them (use with (c) { ... }).

@property St sidebar()

st.sidebar

@property St topbar()

st.topbar: the right side of the header bar, for small items such as buttons, menuButton or userMenu (streamlitd only).

@property St footer()

st.footer: the area under the main content, on every page (streamlitd only).

St card(string title = null, string subtitle = null, string image = null, string icon = null, string key = null, string link = null)

A card (streamlitd only): a framed box with an optional image (URL) or icon, a title and a subtitle. Returns its body; put text, metrics and buttons in it. Use st.columns for a grid. With link (an app page's URL path, or an http(s) URL) the whole card is a link; buttons in it still work.

St container(bool border = false, int height = 0, string key = null)

st.container. height > 0 makes it scrollable.

void container(scope void delegate(St) body_, bool border = false, int height = 0)

st.container with a body.

St[] columns(size_t n, string gap = "small", string verticalAlignment = "top", bool border = false)

st.columns(n)

St[] columns(double[] spec, string gap = "small", string verticalAlignment = "top", bool border = false)

st.columns([2, 1, 1]) — relative widths.

St expander(string label, bool expanded = false, string icon = null)

st.expander

void expander(string label, scope void delegate(St) body_, bool expanded = false)

st.expander with a body.

St popover(string label, string help = null, bool disabled = false, bool useContainerWidth = false)

st.popover

St[] tabs(string[] labels)

st.tabs

St form(string key, bool clearOnSubmit = false, bool border = true, bool enterToSubmit = true)

st.form — widgets inside only send their values when the submit button is pressed.

void form(string key, scope void delegate(St) body_, bool clearOnSubmit = false, bool border = true)

st.form with a body.

St empty()

st.empty — a single-element placeholder. Every call on the returned generator replaces its content.

St chatMessage(string name, string avatar = null)

st.chat_message — a chat bubble container. name "user"/"assistant" pick default avatars.

void chatMessage(string name, scope void delegate(St) body_, string avatar = null)

st.chat_message with a body.

Partial reruns: fragments, dialogs, status

Source: source/streamlitd/fragments.d

struct FragmentRef

Handle returned by st.fragment: rerun that fragment on demand. Keep it (e.g. in st.session or your own registry) and call refresh() from anywhere: a file watcher, a queue consumer, a background thread. Thread-safe; does nothing once the browser tab is closed or the fragment is no longer drawn. For events that concern every open tab, use refreshOn with refreshFragments(topic) instead.

bool refresh()

Rerun the fragment now (without waiting for runEvery). Returns whether it was queued.

bool alive()

Is the fragment still on an open page? (Its last full run drew it.)

@property string id() const

The fragment's id ("fk:<key>" with a key).

size_t refreshFragments(string topic)

Rerun every fragment drawn with refreshOn: topic, in every open browser tab, now, without waiting for runEvery. Thread-safe: call it from API routes, background threads, file watchers or app code. Returns the number of fragments queued.

final class StatusContainer

Handle returned by st.status: a container (use it like st) whose label/state can change.

void update(string label = null, string state = null, int expanded = -1)

Change label, state ("running", "complete", "error") and/or expansion (-1 = keep, 0/1).

FragmentRef fragment(void delegate(St) body_, double runEvery = 0, string key = null, bool delegate() refreshWhen = null, string refreshOn = null)

st.fragment: the body reruns on its own when a widget inside it changes, without rerunning the whole app. runEvery (seconds) reruns it periodically (live dashboards). Pass a lambda (St f) { ... }; for a named function use toDelegate(&fn). Event-driven updates (streamlitd only): refreshWhen is asked each time a runEvery run is due, and false skips that run (nothing runs, nothing is sent) until the next period; it runs on the server's event loop, so keep it light (a version counter, a file's modification time). refreshOn subscribes the fragment to topics (comma-separated), which refreshFragments(topic) reruns at once in every open tab, from any thread. The returned FragmentRef reruns this fragment in this tab with refresh().

void dialog(string title, void delegate(St) body_, string width = "small", bool dismissible = true, string key = null, void delegate() onDismiss = null)

st.dialog: shows a modal dialog. Its widgets rerun only the dialog. The dialog stays open while it reruns and closes on the next full rerun in which it is not opened again (e.g. after st.rerun()), or when the user dismisses it. Called while a dialog's body runs, it opens a dialog on top of that one (streamlitd only): Esc and × close the top one, and the one below keeps its state. A dialog opened because of a session value (if (st.session.get!bool("editing")) st.dialog(...)) would open again on the next full rerun after the user closed it. onDismiss fixes that: closing it with ×, Esc or a click outside reruns the app and calls onDismiss first, e.g. onDismiss: { st.session.remove("editing"); }.

StatusContainer status(string label, bool expanded = false, string state = "running")

st.status: an expandable container showing the state of a long task.

Data display

Source: source/streamlitd/dataelements.d

DataFrame applyEditorState(DataFrame src, Json state, out long[] rowMap, const ColumnConfig[string] config = null, const string[] disabledCols = null, size_t maxRows = 0)

Apply a data_editor state ({edited, added, deleted}) to a frame. Returns the resulting frame and fills rowMap with the source of each output row (original row index, or -(k+1) for the k-th added row).

Json coerceCell(Json v, ColumnType t)

Convert an edited value coming from the browser to the column type.

struct TableCell

A cell picked in a single-cell selection.

struct TableSelection

What the viewer selected in an st.dataframe(..., onSelect: "rerun").

bool empty() const

Nothing selected?

TableSelection dataframe(DataFrame df, int height = 0, bool hideIndex = false, bool useContainerWidth = true, string[] columnOrder = null, ColumnConfig[string] columnConfig = null, string[string] totals = null, string delegate(size_t row, string column, Json value) cellStyle = null, int maxHeight = 0, string onSelect = "ignore", string selectionMode = "single-row", string rowKey = null, string key = null, string[] groupBy = null, int expanded = 0, void delegate() onChange = null)

st.dataframe — interactive table: sort by clicking a header, search, CSV download. - columnConfig: per column label, format, width, tooltip, pinned/hidden, colours, grouped headers (see ColumnConfig); - totals: a row pinned at the bottom: per column "sum", "mean", "min", "max", "count" or a text such as "Total" (computed over the rows shown, after search); - cellStyle: style tokens per cell ("bg:success", "text:error", "bold", "bg:#fff3cd"; several separated by spaces), or null; - height: fixed height in pixels; maxHeight: grow with the rows up to this height (default: 400 px). Selection: with onSelect: "rerun" the table is a widget; clicking a row (or cell) reruns the app and returns the selection. selectionMode: "single-row" (click again to clear), "multi-row" (checkboxes, Shift-click for ranges) or "single-cell". rowKey names a column whose values identify rows (selection.keys; the selection then survives filtering). Keyboard: ↑/↓ move between rows, Space or Enter selects. Tree rows: groupBy: ["manager", "supplier"] groups the rows into levels that open and close (←/→ with the keyboard), with group values aggregated by totals; sorting keeps rows under their group. expanded levels are open at first.

void dataframe(Json records, int height = 0, bool hideIndex = false)

st.dataframe for JSON records.

void table(DataFrame df, bool hideIndex = false, ColumnConfig[string] columnConfig = null, string[string] totals = null, string delegate(size_t row, string column, Json value) cellStyle = null)

st.table — static table (no sorting or scrolling); columnConfig, totals and cellStyle work as in dataframe.

DataFrame dataEditor(DataFrame df, string key = null, string numRows = "fixed", string[] disabled = null, bool hideIndex = false, int height = 0, void delegate() onChange = null, bool disabledAll = false, ColumnConfig[string] columnConfig = null, string[] columnOrder = null, size_t maxRows = 0)

st.data_editor — editable table; returns the edited frame. numRows: "fixed" or "dynamic" (allows adding/deleting rows). columnConfig chooses the editors (ColumnConfig.select(options) is a drop-down, number has min/max/step, checkbox, date, ...); edits it does not allow are dropped on the server too. maxRows (with numRows: "dynamic") limits how many rows the table may have: "+ Add row" stops there, and rows added beyond it are ignored on the server (0 = no limit).

Column configuration (ColumnConfig)

Source: source/streamlitd/columnconfig.d

See Data & charts.

struct ColumnConfig

How one column is shown (and edited). Make one with the static functions (ColumnConfig.number, ColumnConfig.date, ...); every argument is optional.

static ColumnConfig text(string label = null, string help = null, string width = null, bool pinned = false, bool disabled = false, size_t maxChars = 0, bool required = false, string color = null, string background = null, string group = null, bool hidden = false)

A text column.

static ColumnConfig number(string label = null, string format = null, string help = null, string width = null, double min = double.nan, double max = double.nan, double step = double.nan, bool pinned = false, bool disabled = false, bool required = false, string color = null, string background = null, string detailColumn = null, string group = null, bool hidden = false)

A number column.

static ColumnConfig date(string label = null, string format = null, string help = null, string width = null, bool pinned = false, bool disabled = false, bool required = false, string group = null)

A date column (values "YYYY-MM-DD").

static ColumnConfig datetime(string label = null, string format = null, string help = null, string width = null, bool pinned = false, bool disabled = false, string group = null)

A date-and-time column (values "YYYY-MM-DDTHH:MM:SS").

static ColumnConfig time(string label = null, string format = null, string help = null, string width = null, bool disabled = false, string group = null)

A time column (values "HH:MM" or "HH:MM:SS").

static ColumnConfig checkbox(string label = null, string help = null, string width = null, bool disabled = false, string group = null)

A true/false column (a checkbox in the editor).

static ColumnConfig select(string label = null, string[] options = null, bool required = false, string help = null, string width = null, bool disabled = false, string group = null)

A column whose values come from options (a themed drop-down in the editor).

static ColumnConfig progress(string label = null, double min = 0, double max = 100, string format = null, string help = null, string width = null, string group = null)

A progress bar between min and max, with the value as its label.

static ColumnConfig link(string label = null, string displayText = null, string help = null, string width = null, string group = null)

A link (the URL is the value); displayText replaces the URL in the cell.

static ColumnConfig column(string label = null, string help = null, string width = null, bool pinned = false, bool disabled = false, string group = null)

Only a header label, tooltip, width or group; the type comes from the data.

static ColumnConfig hide()

A column that is not shown (see the hidden field).

Json toJson() const

The JSON sent to the browser.

Calendar grid

Source: source/streamlitd/calendar.d

See More elements.

struct GridRow

A row of st.calendarGrid. Rows with a parent are shown under it, when it is opened.

struct GridItem

An item on the grid: a marker on one day, or a span from start to end.

struct GridEvent

What was clicked in a st.calendarGrid (on the run triggered by the click only).

bool opCast(T : bool)() const

Did something get clicked in this run?

GridEvent calendarGrid(GridRow[] rows, GridItem[] items, Date start, Date end, string unit = "day", string key = null, string focus = null, int height = 0, Date today = Date.init, string summaryLabel = null, int expanded = 0)

A calendar grid (streamlitd only): one row per GridRow (rows with a parent open under it), one column per day (or week) from start to end, with markers and spans. Weekends, today and month starts are marked. Clicking an item, a row name or an empty day reruns the app and returns a GridEvent (like a button: only in that run). focus scrolls to an item and highlights it once. Keyboard: arrows move between items, Enter opens. auto ev = st.calendarGrid(rows, items, Date(2026, 11, 1), Date(2026, 12, 31), key: "plan"); if (ev.kind == "item") st.dialog("Delivery", (St d) { d.write(ev.item); });

Charts & maps

Source: source/streamlitd/charts.d

enum indexField

Name of the synthetic index field used when x is not given.

void lineChart(DataFrame df, string x = null, string[] y = null, string color = null, int height = 0, string xLabel = null, string yLabel = null, bool useContainerWidth = true)

st.line_chart

void areaChart(DataFrame df, string x = null, string[] y = null, string color = null, int height = 0, string xLabel = null, string yLabel = null, bool stack = true, bool useContainerWidth = true)

st.area_chart

void barChart(DataFrame df, string x = null, string[] y = null, string color = null, int height = 0, string xLabel = null, string yLabel = null, bool stack = true, bool horizontal = false, bool useContainerWidth = true)

st.bar_chart

void scatterChart(DataFrame df, string x = null, string[] y = null, string color = null, string size = null, int height = 0, string xLabel = null, string yLabel = null, bool useContainerWidth = true)

st.scatter_chart

void vegaLiteChart(Json spec, DataFrame data = null, bool useContainerWidth = true)

st.vega_lite_chart — any Vega-Lite spec; if data is given it becomes the spec's data.

void vegaLiteChart(string spec, DataFrame data = null, bool useContainerWidth = true)

ditto, spec as JSON text.

void map(DataFrame df, string latitude = null, string longitude = null, string size = null, double radius = 0, string color = null, double zoom = -1, int height = 400, bool useContainerWidth = true)

st.map — points on an interactive map (Leaflet). Latitude/longitude columns are detected automatically (lat/latitude, lon/lng/longitude) unless named. size names a column with the radius in meters (or use radius for all points); color is a hex color or a column with hex colors. Tiles come from OpenStreetMap unless [map] tileUrl is configured.

Json plotlyChart(Json figure, bool useContainerWidth = true, string theme = "streamlit", int height = 0, string key = null, string onSelect = "ignore")

st.plotly_chart — renders a Plotly figure ({"data": [...], "layout": {...}}, e.g. from fig.to_json() in Python or built in D). theme: "streamlit" applies the active design style; pass null for Plotly's own look. With onSelect: "rerun" the chart acts as a widget and returns the current selection ({"points": [...]}, or null).

Json plotlyChart(string figureJson, bool useContainerWidth = true, string theme = "streamlit", int height = 0, string key = null, string onSelect = "ignore")

ditto, figure as JSON text.

Media, files & downloads

Source: source/streamlitd/mediaelements.d

void image(const(ubyte)[] data, string caption = null, int width = 0, string mime = null, bool useContainerWidth = false)

st.image from encoded bytes (PNG, JPEG, GIF, WebP, SVG).

void image(string pathOrUrl, string caption = null, int width = 0, bool useContainerWidth = false)

st.image from a file path or an http(s)/data URL.

void setFavicon(string emojiUrlOrPath)

The page favicon: an emoji, an http(s)/data URL, or a local image file (served from the app). Same as st.setPageConfig(icon: ...).

void setFavicon(const(ubyte)[] data, string mime = null)

ditto, from image bytes (png, svg, ico, ...).

void logo(string pathOrUrl, string link = null, string size = "medium")

st.logo: an image shown at the top of the sidebar, or in the top-left corner of the page while the sidebar is hidden (no sidebar content) or collapsed.

void logo(const(ubyte)[] data, string link = null, string size = "medium", string mime = null)

ditto, from image bytes.

void audio(const(ubyte)[] data, string mime = "audio/wav")

st.audio from bytes or a path/URL.

void video(const(ubyte)[] data, string mime = "video/mp4")

st.video from bytes.

void audio(string pathOrUrl)

st.audio from a file path or an http(s)/data URL.

void video(string pathOrUrl)

st.video from a file path or an http(s)/data URL.

bool downloadButton(string label, const(ubyte)[] data, string fileName, string mime = "application/octet-stream", string key = null, string help = null, void delegate() onClick = null, bool disabled = false, string type = "secondary", bool useContainerWidth = false, string icon = null)

st.download_button — returns true on the run triggered by the click.

void downloadButton(string label, const(ubyte)[] delegate() build, string fileName, string mime = "application/octet-stream", string key = null, string help = null, bool disabled = false, string type = "secondary", bool useContainerWidth = false, string icon = null)

ditto, with the file built only when it is clicked (not on every run), e.g. an Excel export (streamlitd only). build runs on its own thread, so a slow export does not hold up other sessions. The link works while the button is on the page. No rerun happens on click.

void downloadButton(string label, string delegate() build, string fileName, string mime = "text/plain", string key = null, string help = null, bool disabled = false, string type = "secondary", bool useContainerWidth = false, string icon = null)

ditto, text built on click.

bool downloadButton(string label, string data, string fileName, string mime = "text/plain", string key = null, string help = null, void delegate() onClick = null, bool disabled = false, string type = "secondary", bool useContainerWidth = false, string icon = null)

ditto, text data.

UploadedFile fileUploader(string label, string[] type = null, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.file_uploader — returns the uploaded file or null. type lists accepted extensions, e.g. ["csv", "txt"].

UploadedFile[] fileUploaderMulti(string label, string[] type = null, string key = null, string help = null, void delegate() onChange = null, bool disabled = false, string labelVisibility = "visible")

st.file_uploader(accept_multiple_files=True)

Navigation (multipage)

Source: source/streamlitd/pages.d

struct Page

A page of a multipage app.

void run(St st)

Run the page's function.

string slugify(string title)

URL slug of a title.

Page navigation(Page[] pages, string position = "sidebar", string sections = "headings")

st.navigation — declares the pages and returns the selected one; call .run(st) on it. position: "sidebar", "top" (links in the header bar; sections become dropdowns, and on narrow screens everything moves into a ☰ menu) or "hidden". Group pages with Page.section. sections: "headings" (default) or "collapsible": in the sidebar, sections fold, and the current page's section is open.

void switchPage(string page)

st.switch_page — switch to another page (by url path or title) and rerun.

void pageLink(string urlPath, string label, string icon = null)

st.page_link

void breadcrumbs()

Breadcrumbs for the current page, from st.navigation: the default page › the page's section › the page (streamlitd only). Call it after st.navigation, e.g. at the top of a page.

void breadcrumbs(string[] labels, string[] urlPaths = null)

Breadcrumbs with an explicit trail (streamlitd only). urlPaths[i] makes item i a link to that app page (null or missing: plain text); the last item is the current position.

string userMenu(string[] items = null, bool logout = true, string key = null, bool account = true, bool rerun = false, bool appearance = false)

The user menu in the header bar: the logged-in user's picture (or initials) and name, opening a menu with items and "Log out". Returns the item clicked in this run, otherwise null. Signed out, it shows a "Log in" button; without [auth] configured it shows nothing. It is always placed in st.topbar, wherever it is called. With account, users from the user store also get "Account settings" (name, email, password: /auth/account). rerun and appearance add "Rerun" and "Appearance…" (the header's ⟳ and ⚙, e.g. with [ui] rerunButton = "hidden").

Custom components

Source: source/streamlitd/components.d

struct ComponentSource

Where a declared component's frontend comes from.

ComponentSource* findComponent(string name)

Look up a declared component (used by the server).

struct Component

A declared bidirectional component; call it like a widget.

Json opCall(St st, Json args = Json.emptyObject, string key = null, Json default_ = Json(null), int height = 0)

Render the component and return its current value (default_ until it sends one).

Component declareComponent(string name, string path = null, string html = null, string url = null)

Declare a component (components.declare_component). Give exactly one of path (directory containing index.html), html (inline page) or url (dev server).

struct ComponentsApi

st.components API (static HTML and iframes).

void html(string body_, int height = 150, bool scrolling = false)

components.html: render HTML in a sandboxed iframe.

void iframe(string src, int height = 150, bool scrolling = false, int width = 0)

components.iframe: embed a URL.

@property ComponentsApi components()

st.components.html(...), st.components.iframe(...)

void iframe(string src, int height = 150, bool scrolling = false, int width = 0)

st.iframe(url)

Json customComponent(string name, Json args, string key, Json default_, int height)

Render a declared component (prefer Component.opCall).

Custom elements & widgets

Source: source/streamlitd/extensions.d

See Extending streamlitd.

struct CustomElement

A registered custom element: its browser code and styles.

void registerElement(string name, string js = null, string css = null, string jsPath = null, string cssPath = null)

Register a custom element or widget: js (or the file jsPath) renders it in the browser, css (or cssPath) styles it. Use it in the app with st.customElement(name, props) or st.customWidget!T(name, label, default_, ...). Call it before the server starts, e.g. in shared static this(); [elements.<name>] in config.toml does the same with file paths.

bool isElementRegistered(string name)

True if name was registered with registerElement.

string[] elementNames()

Names of all registered custom elements.

struct ElementScript

One element's script, served at _stcore/ext/<name>.js.

struct ExtensionAssets

The extension files: one stylesheet (_stcore/ext.css, empty = none) and one script per element. Separate scripts keep a syntax error in one element from stopping the others.

const(ElementScript)* script(string name) const

The script of element name, or null.

void customElement(string name, Json props = Json.emptyObject)

Render a registered custom element that shows something but has no value. props reaches its renderer as el.props.

T customWidget(T)(string name, string label, T default_, Json props = Json.emptyObject, string key = null, void delegate() onChange = null, bool disabled = false, string help = null, string labelVisibility = "visible", bool trigger = false)

Render a registered custom widget and return its value: default_ until the browser sends one with api.setValue(v). The value is decoded into T on the server; anything that does not decode gives default_. Works with key, st.session, onChange, forms and fragments. trigger: true makes a button-like widget: api.trigger(v) returns v for that one run only. Always give T explicitly: st.customWidget!int("rating", "Stars", 3, key: "r").

App control, page config, themes, auth (St core)

Source: source/streamlitd/delta.d

enum RootContainer : int

Root containers.

final class St

The DeltaGenerator: the object passed to the app function (st) and returned by container calls (st.sidebar, st.columns(2)[0], st.expander("x") ...).

@property SessionState session()

The per-session state (st.session_state).

@property Secrets secrets()

st.secrets — values from .streamlitd/secrets.toml (never sent to the browser).

@property RequestContext context()

st.context: the browser request behind this session: headers, cookies, client address, language, time zone and page URL (e.g. to read a single-sign-on cookie of a portal).

void resetWidgets(string[] keys...)

Forget the values of these keyed widgets: they show their defaults from this run on (e.g. after saving a form, instead of changing keys).

@property UserInfo user()

st.user: the logged-in user (see [auth] configuration).

void login(string provider = null)

st.login: send the browser to the login page (or straight to provider).

void logout()

st.logout: clear the login cookie.

@property AppSession appSession()

The underlying session object.

void stop()

Stop the current run (st.stop()).

void rerun(string scope_ = "app")

Rerun immediately (st.rerun()). scope_: "fragment" reruns only the current fragment when called during a fragment run; otherwise the whole app reruns.

void sleep(double seconds)

Sleep without blocking other sessions (yields to the event loop).

void setPageConfig(string title = null, string icon = null, Layout layout = Layout.centered, string initialSidebarState = "auto", string theme = null, bool allowThemeSwitch = true, string colorScheme = null, string design = null, string rerunButton = null, string settingsButton = null)

Configure the page (st.set_page_config). icon is the browser-tab favicon: an emoji, an http(s)/data URL, or a local image file. colorScheme (alias theme) and design select the color scheme and design style (see colorSchemeNames, designNames); allowThemeSwitch: false hides the viewer's appearance menu. rerunButton and settingsButton ("header", "menu" or "hidden") move the header's ⟳ and ⚙ (default: [ui] in config.toml); they apply until changed.

void setTheme(string scheme = null, string mode = null, string design = null)

Change the color scheme, mode ("auto", "light", "dark") and/or design style. Parts left null keep their current value: st.setTheme(design: "terminal") only changes the design.

void setTheme(Theme theme, bool allowThemeSwitch = true)

Set a full theme: color scheme + mode + design style + Streamlit-style overrides (primaryColor, font, ...). allowThemeSwitch: false hides the viewer's appearance menu; the lock holds for the rest of the run (later partial setTheme calls keep it).

Theme currentTheme()

The theme last set by the app in this session (or the server default).

void toast(string body_, string icon = null)

Show a toast notification (st.toast).

void balloons()

Celebrate (st.balloons).

void snow()

Celebrate (st.snow).

@property QueryParams queryParams()

Current URL query parameters (st.query_params).

struct RequestContext

The browser request behind a session (st.context), taken when the page connected; locale, timezone and url follow the browser.

string header(string name) const

A header by name, in any case, or null.

string cookie(string name) const

A cookie by name, or null.

struct UserInfo

The logged-in user (st.user).

@property bool isLoggedIn() const @trusted

True when a user is logged in.

@property string name() const @trusted

Display name.

@property string email() const @trusted

E-mail address (if the provider shares it).

@property string sub() const @trusted

Stable subject id from the provider (username for password logins).

@property string provider() const @trusted

"password" or the OIDC provider name.

@property string username() const @trusted

The account name in the user store: the username for password users, "<provider>:<sub>" for OIDC users (what st.accounts methods take).

@property string[] roles() const @trusted

Roles: from the user store, roles in [auth.users.x], and "admin" for [auth] admins.

bool hasRole(string role) const @trusted

Has the user this role?

@property bool isAdmin() const

Has the user the "admin" role?

@property Json claims() const @trusted

All stored claims.

struct QueryParams

Access to the browser's URL query string.

string get(string name, string def = null)

Value of a parameter, or def.

string opIndex(string name)

st.queryParams["x"]

void opIndexAssign(string value, string name)

Set a parameter (updates the browser URL).

void remove(string name)

Remove a parameter.

void clear()

Remove all parameters.

string[string] toAA()

All parameters.

Accounts on St: roles, admin panel

Source: source/streamlitd/useradmin.d

See Authentication.

@property Accounts accounts()

The account service (sign-up, users, roles, invites, reset links); see streamlitd.accounts. Passwords given to it are hashed automatically. Throws when [auth] is not configured.

void requireLogin()

Stop the run and send the browser to the login page when nobody is logged in.

void requireRole(string role)

Show an error and stop the run unless the logged-in user has role (e.g. "admin"); sends anonymous visitors to the login page.

void userAdmin(string key = "user-admin")

A ready-made user administration panel (streamlitd only), for admins: the users with their roles and status; approve, disable, reset links, log out everywhere, delete; adding users (passwords are hashed automatically) and one-time invites. Other users see an error. key keeps its widgets apart when there are several panels.

Accounts: sign-up, user store, roles, invites

Source: source/streamlitd/accounts.d

See Authentication.

struct StoredUser

A user in the store. Password users have a passwordHash; users from an OIDC provider have provider set (and username = "<provider>:<sub>").

string status() const

"active", "pending" or "disabled".

struct Invite

A one-time invite (only a hash of its code is stored).

string id() const

Short id for lists and revoking (the start of the hash; not usable to sign up).

class AccountError : Exception

Raised for problems a user should see ("username taken", "password too short", ...).

StoredUser* find(string username)

The user, or null.

StoredUser* findByEmail(string email)

The user with this email (case-insensitive), or null.

StoredUser[] list()

All users, ordered by created.

void insert(StoredUser u)

Add a user; throws AccountError when the username exists.

void update(StoredUser u)

Replace the user with the same username.

Invite* takeInvite(string codeHash)

Remove and return the invite with this code hash, or null (single use).

class MemoryUserStore : UserStore

A store in memory (tests, or apps that only need users until a restart).

protected void changed()

Called after each change (the file store saves here).

class JsonFileUserStore : MemoryUserStore

The default store: a JSON file, written atomically (temporary file + rename) with mode 0600. It is read once at startup; a file that cannot be parsed is an error (never silently reset).

void restrictPermissions(string path)

chmod 600 (owner only) where supported.

Json userToJson(const ref StoredUser u)

A user as a JSON document (the format of users.json); handy for document databases.

StoredUser userFromJson(Json j)

ditto, back from JSON.

enum Registration

Who may create an account ([auth] registration).

Registration parseRegistration(string s)

Parse a registration value ("off", "first_admin", "open", "approval", "invite").

string registrationName(Registration r)

The config name of a registration mode.

string normalizeUsername(string name)

Lowercase and check a username: 3–64 characters a-z 0-9 . _ -, starting with a letter or digit.

string normalizeEmail(string email)

A loose email check (one "@", a dot in the domain, no spaces); returns the trimmed address.

enum maxPasswordLength

Maximum accepted password length (PBKDF2 cost grows with it).

string passwordProblem(string password, size_t minLength, string username = null, string email = null)

Why password is not acceptable, or null.

string sha256Hex(string s)

Hex SHA-256 (invite codes are stored only as this hash).

string randomCode(size_t bytes = 18)

A random URL-safe code.

string hashPasswordSlow(string password)

Hash a new password (PBKDF2; deliberately slow).

bool verifyPasswordSlow(string password, string hash)

ditto, for verifying (unknown users, i.e. an empty hash, cost the same and fail).

struct AccountSettings

Account settings from [auth].

enum LoginResult

Outcome of a password check.

final class Accounts

The account service: one per server (accounts()), shared by the login pages, the CLI and the app (st.accounts). Thread-safe through the store.

immutable(ubyte)[] secret

Signs reset links (the cookie secret).

string configUserKey(string username) const

The key of [auth.users.<name>] matching username without regard to case (usernames are not case sensitive), or null.

Json configUser(string username) const

The [auth.users.<name>] table, or Json.undefined.

bool isConfigUser(string username) const

A user from [auth.users.*] (read-only)?

string[] configRoles(string username, string email = null) const

Roles of a config user: its roles, plus "admin" when listed in admins.

bool isListedAdmin(string username, string email) const

Listed in [auth] admins (by username or email)?

bool isEffectiveAdmin(const ref StoredUser u) const

Has this store user admin rights (the admin role, or listed in admins)?

bool hasAdmin()

Is there an active admin (store, config users or the admins list)?

bool signupOpen()

Can somebody create a password account right now (from the sign-up page)?

bool inviteRequired()

Does the sign-up page need an invite code?

StoredUser register(string username, string password, string name = null, string email = null, string inviteCode = null)

Self sign-up (the registration page). Applies the registration mode: the first account becomes admin (unless admins names the admins; then those users need no invite or approval), approval accounts start pending, invite needs a valid inviteCode. Throws AccountError with a message for the user.

StoredUser createUser(string username, string password, string name = null, string email = null, string[] roles = null)

Create a user (admins, the CLI, app code); no registration-mode checks.

LoginResult checkLogin(string username, string password, out Json user)

Check a username and password (store and config users). user receives the session claims on success. Unknown users cost the same time as wrong passwords.

Json claimsOf(const ref StoredUser u)

Session claims of a store user (stored in the login cookie).

Json resolve(Json claims)

Validate cookie claims against the store and add fresh roles: returns the user, or Json(null) when the account was deleted, disabled, is pending or its logins were ended.

Json oidcSignIn(string provider, string sub, string name, string email, string picture, string inviteCode = null)

An OIDC sign-in: records the user in the store on first sign-in (so admins can give roles or disable them), applies allowed_email_domains, approval and invite. Returns the session claims; throws AccountError when the user may not sign in.

Json changePassword(string username, string current, string newPassword)

Change one's own password (needs the current one). Ends other logins; returns the new claims.

void updateProfile(string username, string name, string email)

Change name and email.

StoredUser* user(string username)

The store user, or null.

StoredUser[] users()

All store users.

void setPassword(string username, string newPassword)

Set a new password (admin or CLI); ends the user's logins.

void setRoles(string username, string[] roles)

Replace the roles.

void setDisabled(string username, bool disabled)

Disable (logins end) or enable an account.

void approve(string username)

Approve a pending account.

void logoutEverywhere(string username)

End all logins of the user (on every device).

void deleteUser(string username)

Delete an account.

string createInvite(string[] roles = null, uint days = 7, string createdBy = null)

Create a one-time invite valid for days days; returns the code (shown once; only its hash is stored). The sign-up link is inviteLink(code).

Invite[] invites()

Open invites (expired ones are removed).

void revokeInvite(string id)

Revoke an invite by its id.

string inviteLink(string code)

The sign-up link for an invite code (a path under the app's base; prefix your host).

string createResetLink(string username, uint hours = 24)

A one-time link to set a new password, valid for hours (a path under the app's base). It stops working once the password changes.

string resetTokenUser(string token)

The user a reset token is for, or null when it is invalid, expired or used.

Json resetPassword(string token, string newPassword)

Set a new password with a reset token; returns the session claims.

void useUserStore(UserStore store)

Use your own user store (e.g. a database) instead of .streamlitd/users.json. Call before serve / in main.

Accounts accounts()

The server's account service (null when [auth] is not configured).

final class LoginThrottle

Counts failed logins per username and per client address and blocks further attempts for a while (in memory; a restart clears it).

bool blocked(string user, string ip)

Too many recent failures for this username or address?

void fail(string user, string ip)

Record a failure.

void succeed(string user)

A successful login clears the username's failures.

string safeNext(string next, string base)

A safe next target after login: a path under the app (base + "/..."), never another site.

Session state (st.session)

Source: source/streamlitd/state.d

final class SessionState

Session state, the D counterpart of st.session_state. Stores arbitrary D values (class instances included) as Variant.

Variant opIndex(string key)

Read a value. Throws StreamlitAPIException if missing.

void opIndexAssign(T)(T value, string key)

Assign a value.

T get(T)(string key, T def = T.init)

Typed read with default.

T setDefault(T)(string key, T def)

Set if missing, then return the (typed) value.

bool has(string key) const

True if the key exists.

bool opBinaryRight(string op : "in")(string key) const

"key" in st.session

void remove(string key)

Remove a key.

string[] keys() const

All keys.

void clear()

Remove all keys.

size_t length() const

Number of keys.

T convertVariant(T)(Variant v, string key = null)

Convert a Variant to T, coercing numeric types.

DataFrame

Source: source/streamlitd/dataframe.d

enum ColumnType

Logical column types (sent to the frontend for formatting/editing).

string typeName(ColumnType t)

Name used in the protocol.

template columnTypeOf(T)

Map a D type to a column type.

Json cellJ(T)(T v)

Convert a cell value to Json.

T cellAs(T)(Json j)

Convert a Json cell to T.

int compareCells(Json a, Json b)

Order Json cells (nulls last).

struct Row

One row view.

Json opIndex(string col)

Raw cell.

T get(T)(string col)

Typed cell.

final class DataFrame

Column-oriented table.

static DataFrame fromStructs(R)(R rows)

Build from a range of structs (or classes); each field becomes a column.

static DataFrame fromRows(string[] names, Json[][] rows)

Build from row arrays.

static DataFrame fromJson(Json records, string[] columnOrder = null)

Build from a JSON array of objects (records). JSON objects do not keep key order, so pass columnOrder to fix the column order; otherwise columns are sorted by name.

static DataFrame fromCsv(string text, dchar separator = ',')

Parse CSV text (first line = header). Column types are inferred.

static DataFrame readCsv(string path, dchar separator = ',')

Read a CSV file.

DataFrame addColumn(T)(string name, T[] values)

Add (or replace) a column. Returns this for chaining.

DataFrame appendRow(Json[] values)

Append a row given as Json cells.

DataFrame appendRow(Args...)(Args values)

Append a row given as D values.

size_t length() const

Number of rows.

size_t width() const

Number of columns.

const(string)[] columns() const

Column names.

const(ColumnType)[] types() const

Column types.

ColumnType typeOf(string col) const

Type of a column.

bool hasColumn(string col) const

True if the column exists.

size_t colIndex(string col) const

Index of a column (throws if missing).

Json cell(size_t row, string col)

Raw cell.

Json cell(size_t row, size_t col)

Raw cell by position.

void setCell(size_t row, string col, Json v)

Set a raw cell.

T[] column(T)(string col)

Typed column values.

Json[] rawColumn(string col)

Raw column values.

Row row(size_t i)

Row view.

int opApply(scope int delegate(Row) dg)

Iterate rows: foreach (row; df) or foreach (i, row; df).

int opApply(scope int delegate(size_t, Row) dg)

ditto

DataFrame dup()

Deep copy.

DataFrame head(size_t n = 5)

First n rows.

DataFrame tail(size_t n = 5)

Last n rows.

DataFrame slice(size_t from, size_t to)

Rows [from, to).

DataFrame select(string[] cols...)

Keep only the named columns, in the given order.

DataFrame drop(string[] cols...)

Drop columns.

DataFrame filter(scope bool delegate(Row) pred)

Rows for which pred is true.

DataFrame sortBy(string col, bool ascending = true)

Sort by a column.

DataFrame rename(string from, string to)

Rename a column.

DataFrame groupBy(string key, string[] valueCols, string agg = "sum")

Group by key and aggregate valueCols with "sum", "mean", "count", "min" or "max".

double sum(string col)

Sum of a numeric column (nulls skipped).

double mean(string col)

Mean of a numeric column.

double min(string col)

Minimum of a numeric column.

double max(string col)

Maximum of a numeric column.

Json toJson()

{columns: [{name, type}], data: [[...row...]]}

Json toRecords()

Array of {column: value} objects.

string toCsv(char separator = ',', bool safe = false)

CSV text. safe: text cells that a spreadsheet would run as a formula (starting with =, +, -, @, Tab or CR, and not a number) get a leading '. Use it for files people open in Excel when the data holds text users typed ("CSV injection").

Caching

Source: source/streamlitd/cache.d

template cacheData(alias fn, long ttlSeconds

Memoize fn by its arguments (@st.cache_data). Shared between all sessions; like Streamlit, callers get a copy (via .dup, e.g. arrays and DataFrame) so mutating the result does not change the cache. ttlSeconds = 0 means no expiry; maxEntries = 0 means unbounded.

template cacheResource(alias fn)

Shared resource cache (@st.cache_resource): the same object is returned to every session.

void cacheClear(alias fn)()

Clear the cache of one function.

void clearAllCaches()

Clear all caches (st.cache_data.clear()).

Blocking calls (blocking)

Source: source/streamlitd/blocking.d

See Threads and blocking.

User text in Markdown (escapeMarkdown)

Source: source/streamlitd/text.d

See Core concepts.

string escapeMarkdown(string s) @safe pure

Escape s so Markdown shows it as typed: no formatting, links, images, colour directives (:red[...]), math ($...$) or HTML. Use it whenever user input goes into st.markdown, st.write, labels, captions, feeds and the like: st.markdown("" ~ escapeMarkdown(ticket.title) ~ "");

Secrets

Source: source/streamlitd/secrets.d

final class Secrets

Read-only access to secrets.

Json opIndex(string key)

st.secrets["db"]["password"]. Throws if the key is missing.

T get(T)(string path, T def = T.init)

Typed read with a dotted path, e.g. get!string("db.password").

bool has(string path)

True if the dotted path exists.

bool opBinaryRight(string op : "in")(string key)

"key" in st.secrets

string[] keys()

Top-level keys.

Json deepMerge(Json a, Json b)

Deep-merge two JSON objects (b wins).

string[] secretsSearchPaths()

Files searched, lowest priority first.

Secrets secrets()

The process-wide secrets (loaded on first use).

void setSecrets(Json root)

Replace the secrets (for tests or custom loading).

Themes

Source: source/streamlitd/theme.d

struct ThemeTokens

Theme values. Every field is optional; null means "inherit from the preset".

ThemeTokens merged(const ThemeTokens o) const

Copy with every non-null field of o applied on top.

bool set(string key, string value)

Set one field by its config name (used for --theme.<key>=<value>). Returns false if unknown.

Json toJson() const

Only the fields that are set.

struct Theme

The theme an app asks for: a color scheme, a mode, a design style and optional overrides.

@property string preset() const

Deprecated alias of scheme (the color schemes used to be called presets).

@property void preset(string v)

ditto

struct DesignStyle

A design style: how the UI is shaped. Colors always come from the color scheme.

DesignStyle[] designStyles()

All design styles, in menu order: the built-in ones (the first is the default), then the app's own (registerDesign, [theme.designs.<name>]).

DesignStyle[] builtinDesigns()

The design styles that ship with streamlitd.

string[] designNames()

Names of all design styles.

const(DesignStyle)* findDesign(string name)

Look up a design style; returns null if unknown.

Json designsJson()

All design styles as JSON (sent to the browser once per session).

struct ThemePreset

A named color scheme (palette), with light and dark variants.

ThemePreset[] themePresets()

All color schemes, in menu order: the built-in ones (the first is the default), then the app's own (registerColorScheme, [theme.schemes.<name>]).

ThemePreset[] builtinPresets()

The color schemes that ship with streamlitd.

string[] colorSchemeNames()

Names of all color schemes.

string[] themePresetNames()

Deprecated alias of colorSchemeNames.

const(ThemePreset)* findPreset(string name)

Look up a preset; returns null if unknown.

void validateTheme(const Theme t, const string[] moreSchemes = null, const string[] moreDesigns = null)

Validate a theme; throws on unknown preset/mode. moreSchemes/moreDesigns are names that will be registered when the server starts (from config.toml).

void registerColorScheme(string name, string label = null, ThemeTokens both = ThemeTokens.init, ThemeTokens light = ThemeTokens.init, ThemeTokens dark = ThemeTokens.init, string base = "streamlit")

Add a color scheme to the viewer menu, Theme(...), [theme] scheme and --color-scheme. Tokens not given come from the base scheme. both applies to light and dark mode; light and dark win over it. Colors are #rgb or #rrggbb. linkColor follows primaryColor unless it is set. Call it before the server starts, e.g. in shared static this(): ThemeTokens acme; acme.primaryColor = "#0055aa"; registerColorScheme("acme", "Acme Corp", both: acme);

void registerDesign(DesignStyle style, string css = null, string cssPath = null)

Add a design style. css (or the file cssPath) holds its rules, each scoped by :root[data-design="<name>"] (and .dc-preview[data-design="<name>"] for its card in the appearance menu); see docs/theming.md. Call it before the server starts.

Json presetsJson()

All presets as JSON (sent to the browser once per session).

Json themeJson(const Theme t, bool allowSwitch)

A theme as JSON.

Server & configuration

Source: source/streamlitd/config.d

struct ApiDocsOptions

OpenAPI schema and Swagger UI for the app's API endpoints ([api], see docs/api-endpoints.md).

struct ColorSchemeConfig

A color scheme from [theme.schemes.<name>] (see registerColorScheme).

struct DesignConfig

A design style from [theme.designs.<name>] (see registerDesign).

struct ElementConfig

A custom element's browser files from [elements.<name>] (see registerElement).

struct UiOptions

Server settings (see serve). Where the header's rerun (⟳) and appearance (⚙) buttons go ([ui]).

string uiPlacement(string v, string what)

Check a [ui] placement value ("header", "menu", "hidden").

struct UserCommand

A user-management command given on the command line.

string[] configSearchPaths()

Config files searched, lowest priority first.

Json loadConfigFiles(string explicitPath = null)

Load and merge all config files (or just explicitPath if given).

string[] applyConfig(ref ServerOptions o, Json cfg)

Apply a parsed config ([server], [theme], [map], [auth]) to the options. Unknown keys (e.g. Streamlit-only options such as runOnSave or a [browser] section) are ignored and returned as warnings, so existing .streamlit/config.toml files work.

bool boolValue(Json v, string what)

true/false, 1/0, yes/no, on/off.

string streamlitFont(string v)

Map Streamlit's font keywords ("sans serif", "serif", "monospace") to font stacks; anything else is used as a CSS font-family as is.

void applyEnv(ref ServerOptions o, string[string] env)

Apply STREAMLITD_SERVER_<KEY> / STREAMLITD_THEME_<KEY> / STREAMLITD_API_<KEY> environment variables (e.g. STREAMLITD_SERVER_PORT=8080, STREAMLITD_THEME_PRESET=ocean, STREAMLITD_API_DOCS=true).

string normalizeBasePath(string p)

Normalize a base path: "" or "/prefix" (leading slash, no trailing slash).

Server, app routes & JSON API endpoints

Source: source/streamlitd/server.d

See JSON API endpoints.

enum maxClientMessage

Largest accepted client message (bytes).

void loadFavicon(string path, out immutable(ubyte)[] data, out string mime)

Load the configured favicon file; throws if it cannot be read.

alias RoutesFn

Registers your own HTTP routes (JSON APIs, webhooks, REST interfaces) on the app's server. See StreamlitMain!(app, routes) and docs/api-endpoints.md.

void checkUserRoute(string pattern, const string[] extra = null)

Throws if pattern (a route registered by the app) collides with streamlitd's own routes. extra adds exact reserved paths (the API docs paths when they are served).

UserInfo apiUser(HTTPServerRequest req, HTTPServerResponse res) @trusted

The logged-in streamlitd user for an API request (not logged in when auth is off). Usable as a vibe.d REST @before!apiUser("user") filter.

UserInfo requireUser(HTTPServerRequest req, HTTPServerResponse res) @trusted

Like apiUser, but answers 401 when nobody is logged in. Usable as a vibe.d REST @before!requireUser("user") filter.

UserInfo requireRole(HTTPServerRequest req, HTTPServerResponse res, string role) @trusted

Like requireUser, but also answers 403 unless the user has role (e.g. "admin"). r.delete_("/api/items/:id", (req, res) { requireRole(req, res, "editor"); ... });

int serve(AppFn app, ServerOptions opts = ServerOptions.init, RoutesFn routes = null)

Start serving app and run the event loop (blocks). routes adds your own HTTP routes (e.g. a JSON API) under the same port and base path.

string[] parseThemeOverrides(string[] args, ref ThemeTokens overrides)

Extract --theme.<key>=<value> arguments into overrides; returns the remaining args.

enum ArgsAction

What runMain should do after parsing the command line.

ServerOptions parseServerArgs(string[] args, string[string] env, out ArgsAction action, out string helpText, bool readConfigFiles = true)

Build the server options from config files, STREAMLITD_* environment variables and the command line (precedence: CLI > env > config file > defaults). Throws on invalid input. helpText is filled when --help was given.

int runMain(AppFn app, string[] args, RoutesFn routes = null)

Parse configuration (config.toml, STREAMLITD_* env vars, command line) and serve. Precedence: CLI > env > config file > defaults.

OpenAPI & Swagger UI

Source: source/streamlitd/openapi.d

See OpenAPI and Swagger UI.

struct ApiDoc

Summary and description of an API method in the OpenAPI document (@apiDoc("List todos")).

ApiDoc apiDoc(string summary, string description = null) @safe pure nothrow

ditto

URLRouter registerApi(TImpl)(URLRouter router, TImpl impl, RestInterfaceSettings settings = null)

Register a REST interface implementation (as vibe.d's registerRestInterface does) and add it to the app's OpenAPI document. Use it inside the routes function of StreamlitMain!(app, routes).

struct AppRoute

A route of the app (method + router pattern), as seen by the server.

struct ApiRegistry

Operations and component schemas collected by registerApi.

string openApiPath(string pattern) @safe pure

/api/todos/:_id → /api/todos/{id}.

Json schemaOf(T)(ref ApiRegistry reg)

JSON schema of how vibe.d serializes T (checked in the serializer's order); structs and classes go to reg.schemas and are referenced.

void describeInterface(TImpl)(RestInterfaceSettings settings, ref ApiRegistry reg)

Describe every route of a REST interface implementation into reg.

string buildOpenApiSpec(const ApiDocsOptions opts, string basePath, const AppRoute[] routes, bool authEnabled, bool authRequired, const ref ApiRegistry reg = g_registry)

Build the OpenAPI 3.0 document: the registerApi operations plus every other app route.

string toOrderedJson(Json j)

Pretty JSON with a stable, readable key order (vibe's Json objects don't keep insertion order).

string swaggerPage(string title, string basePath, string specUrl)

The Swagger UI page for specUrl (both under basePath).

string swaggerAsset(string file)

Embedded Swagger UI file (swagger-ui-bundle.js, swagger-ui.css), or null.

Testing (AppTest)

Source: source/streamlitd/testing.d

final class AppTest

Runs an app without a browser and inspects its output.

AppTest run()

Run the app (applying pending updates) until no rerun is pending.

Json[] elements(string kind = null)

All elements of the last run, in document order (optionally of one kind).

Json[] customElements(string name)

Custom elements and widgets of the last run (st.customElement, st.customWidget) named name.

Json widget(string kind, string label)

Find a widget by kind and label.

string widgetId(string kind, string label)

Find a widget id by kind and label.

AppTest setValue(string kind, string label, Json value)

Queue a new widget value (call run() afterwards).

AppTest setValueById(string id, Json value)

Queue a value by widget id.

AppTest click(string label, string kind = "button")

Click a button (call run() afterwards).

int runCount()

Number of script runs (full and fragment) started so far.

AppTest loginAs(string username, string[] roles = null, string name = null, string email = null)

Act as a logged-in user (st.user), e.g. at.loginAs("ann", ["admin"]). A user of the account service set with useAccounts is taken from its store (its roles count then).

AppTest selectRows(string key, size_t[] rows...)

Select rows of an st.dataframe(..., onSelect: "rerun", key: key) (call run() afterwards).

AppTest selectGroup(string key, string[] path...)

Select a group row of a tree table (groupBy) by its path (call run() afterwards).

int[][] paths(string block)

Paths of the containers of one block kind ("dialog", "card", "expander", ...) in page order, e.g. to check that one is drawn inside another.

AppTest trigger(string key, Json value)

Send an event to a keyed widget that triggers a run, e.g. a click in st.calendarGrid(..., key: key): at.trigger("plan", Json(["kind": Json("row"), "row": Json("acme")])).

AppTest dismissDialog(string title)

Close a dialog like the user does with × or Esc (call run() afterwards). Without onDismiss the server never hears of it, so this throws.

AppTest setContext(RequestContext c)

Set st.context (request headers, cookies, address, language, time zone, URL).

AppTest logout()

Log out (st.user.isLoggedIn becomes false).

static void useAccounts(Accounts a)

Use this account service for st.accounts and st.userAdmin (it is process-wide, like on the server; pass null to remove it). Example: at.useAccounts(new Accounts(AccountSettings.init, new MemoryUserStore, Json.emptyObject, secret)).

AppTest chat(string message)

Submit a chat message (call run() afterwards).

AppTest submitForm(string buttonLabel, Json[string] updates = null)

Submit a form: sends the given updates together with the submit button trigger.

string[] texts(string kind)

Body texts of an element kind (markdown, heading, alert, text, code ...).

Json[] exceptions()

Exceptions shown on the page.

Json[] messages(string type)

Messages of a given type sent in the last run (e.g. "toast").