Skip to main content

Crate slackblocks

Crate slackblocks 

Source
Expand description

§slackblocks for Rust

Rust MSRV crates.io docs.rs Rust CI Docs

A native Rust implementation of Slack Block Kit, using coordinated version 2.7.0 and shared specification 1.2.0.

Rust 2024; minimum supported Rust version (MSRV) 1.85. Values own their data, builders consume themselves, getters borrow, and invalid input returns ValidationError. The core depends only on Serde and serde_json.

All shared model types are implemented. Independent native examples and checked JSON ingress cover every shared valid fixture and invalid case. See the implementation plan for the train and acceptance evidence.

§Installation

Add the crate and serde_json to your application:

cargo add slackblocks@2.7.0
cargo add serde_json
use slackblocks::{ButtonElement, MessagePayload, SectionBlock};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let button = ButtonElement::builder().text("Open build").action_id("open_build").build()?;
    let section = SectionBlock::builder().text("Build passed").accessory(button).build()?;
    let message = MessagePayload::builder("C01234567")
        .text("Build passed")
        .block(section)
        .build()?;
    let edited = message.clone().into_builder().text("Build passed on main").build()?;
    assert_eq!(message.text(), Some("Build passed"));
    println!("{}", serde_json::to_string(&edited)?);
    Ok(())
}

§Native API conventions

  • Builders consume themselves; build() returns Result<T, ValidationError>. Built values have private fields, own their data, and expose borrowed getters.
  • Clone a value before into_builder() when both versions are needed. Plural collection setters replace; singular setters append. Iterators are accepted.
  • Concrete children convert into role enums with From; unsupported roles fail at compile time. Vocabulary and role enums are #[non_exhaustive].
  • SelectOption, SelectOptionGroup, and ConfirmationDialogue avoid ambiguous Rust names. No SDK class hierarchy is copied into the crate.
  • Strings coerce according to each text field. Use PlainText or MarkdownText explicitly when you need flags or a particular allowed text kind.
  • Fresh builders use documented model defaults. Checked parsing and editing preserve omitted fields; clear_*() removes optional defaults. Allowed false, zero and empty values remain present. Block IDs are omitted unless supplied.
  • Every modeled value supports Serde serialization and checked deserialization, plus TryFrom<serde_json::Value> for structured ValidationError access. This is outbound Block Kit parsing, not an arbitrary Slack event decoder.
  • Extensions preserve unknown JSON but reject empty keys, modeled fields and type collisions. BuilderPayload::Raw is an explicit unvalidated preview input.
  • JsonNumber preserves i64/u64 integers and finite floating-point values; unsupported precision and nonfinite inputs are rejected. The crate enables serde_json’s arbitrary_precision feature to check original JSON literals before narrowing them to the supported numeric range. A caller-supplied value already rounded before conversion cannot recover its original literal. Text lengths count Unicode code points.

§Helpers and transport

AccordionSection and Accordion compose collapsible containers. Paginator uses one-based pages and .previous/.next action IDs; applications handle the interaction and render the requested page. Both expand into ordinary Block values, so the receiving message/view validates aggregate constraints.

Workflow::from_url accepts ordered input parameters and omits an empty parameter list. AttachmentColor supports named constants and checked hexadecimal parsing. block_kit_builder_url takes borrowed blocks/payloads and creates an encoded URL.

Serialize a MessagePayload, WebhookMessage or MessageResponse through Serde and hand it to an application-owned HTTP client. ModalView and HomeTabView belong inside the appropriate Slack request envelope. The crate makes no network requests and imposes no async runtime. Check Slack’s JSON ok/error response as well as HTTP status. Python’s deprecated legacy attachment Field is outside the shared contract and is deliberately not reproduced.

Runnable Slack Morphism and reqwest examples show authenticated delivery, Slack errors, bounded rate-limit retries and timeouts. The sending guide displays their tested source. The separate application project and its lockfile are verified on Rust 1.85 and stable; HTTP and async dependencies stay outside the published crate. Tests use local mock servers and need no Slack credentials.

§Support and reference

MSRV is 1.85.0; raising it requires an explicit compatibility decision and release notes. CI tests minimum Rust and stable, plus stable on Linux, macOS and Windows. Serde/serde_json use compatible version requirements. Fresh consumers test the declared dependency lower bounds and serde_json feature unification independently of the development lockfile.

Rust support starts at coordinated 2.6.0; no earlier Rust API migration is needed. Read the guides and API reference, or run cargo doc --manifest-path rust/Cargo.toml --no-deps --open for native rustdoc and trait implementations.

§Development

Install stable Rust and Rust 1.85.0 with rustfmt and Clippy, plus Python 3.11+ for the development-only generator. The package itself does not need Python. Formatting is pinned to Rust 1.85.0; current stable owns Clippy and rustdoc checks.

export RUSTFMT="$(rustup which --toolchain 1.85.0 rustfmt)"
python3 rust/generator/generate.py
rust/bin/check
python3 rust/bin/check-package.py --toolchain 1.85.0 --all-consumers
python3 rust/bin/check-package.py --toolchain stable

CI runs stable on Linux, macOS, and Windows and the minimum toolchain on Linux. Package checks extract the actual Cargo archive and compile fresh consumers against that extracted artifact, without access to the checkout’s Rust sources.

Quality checks include independent API and contract audits, property tests, and negative compile checks with a passing companion. CI enforces at least 90% line and 90% region coverage independently for the whole crate and handwritten code:

rustup component add llvm-tools-preview --toolchain stable
cargo +stable install cargo-llvm-cov --version 0.9.1 --locked
python3 rust/bin/check-coverage.py

Only external code, test/example harnesses, and files containing no executable regions are excluded. Coverage is measured on stable Rust; it is not a branch coverage claim. The report also exercises consumer-enabled serde_json features.

For explicit response visibility, replacement and delete-only payloads, see the response URL recipes. WebhookMessage supports native delete_original; MessageResponse does not expose that field.

Structs§

Accordion
A nonempty ordered collection of collapsible sections.
AccordionSection
A validated, collapsible section of an Accordion.
AccordionSectionBuilder
Consuming builder for an accordion section.
ActionsBlock
A block that holds interactive elements such as buttons and menus.
ActionsBlockBuilder
Consuming builder for ActionsBlock. Validation runs in Self::build.
AlertBlock
A severity-labelled alert, available in modals.
AlertBlockBuilder
Consuming builder for AlertBlock. Validation runs in Self::build.
AreaChart
An area chart for a data visualization block.
AreaChartBuilder
Consuming builder for AreaChart. Validation runs in Self::build.
Attachment
A legacy message attachment containing blocks and an optional color bar.
AttachmentBuilder
Consuming builder for Attachment. Validation runs in Self::build.
AttachmentColor
A semantic or six-digit hexadecimal attachment color.
AxisConfig
The categories and labels shared by bar, area, and line chart axes.
AxisConfigBuilder
Consuming builder for AxisConfig. Validation runs in Self::build.
BarChart
A bar chart for a data visualization block.
BarChartBuilder
Consuming builder for BarChart. Validation runs in Self::build.
ButtonElement
An interactive button that sends a payload or opens a URL.
ButtonElementBuilder
Consuming builder for ButtonElement. Validation runs in Self::build.
CardBlock
A compact card with an image, text, and up to three buttons.
CardBlockBuilder
Consuming builder for CardBlock. Validation runs in Self::build.
CarouselBlock
A horizontally scrolling set of cards, available in messages and App Home.
CarouselBlockBuilder
Consuming builder for CarouselBlock. Validation runs in Self::build.
ChannelMultiSelectElement
A menu for selecting multiple public channels.
ChannelMultiSelectElementBuilder
Consuming builder for ChannelMultiSelectElement. Validation runs in Self::build.
ChannelSelectElement
A menu for selecting one public channel.
ChannelSelectElementBuilder
Consuming builder for ChannelSelectElement. Validation runs in Self::build.
ChartSegment
One labelled segment of a pie chart.
ChartSegmentBuilder
Consuming builder for ChartSegment. Validation runs in Self::build.
CheckboxesElement
A group of checkboxes.
CheckboxesElementBuilder
Consuming builder for CheckboxesElement. Validation runs in Self::build.
ColumnSettings
Alignment and wrapping settings for one table column.
ColumnSettingsBuilder
Consuming builder for ColumnSettings. Validation runs in Self::build.
ConfirmationDialogue
A dialog that asks users to confirm an action before it is sent.
ConfirmationDialogueBuilder
Consuming builder for ConfirmationDialogue. Validation runs in Self::build.
ContainerBlock
A titled group of blocks that can optionally collapse.
ContainerBlockBuilder
Consuming builder for ContainerBlock. Validation runs in Self::build.
ContextActionsBlock
A row of feedback or icon buttons, usually shown below AI-generated content.
ContextActionsBlockBuilder
Consuming builder for ContextActionsBlock. Validation runs in Self::build.
ContextBlock
A block of small, secondary images and text.
ContextBlockBuilder
Consuming builder for ContextBlock. Validation runs in Self::build.
ConversationFilter
Limits which conversations a conversation menu offers.
ConversationFilterBuilder
Consuming builder for ConversationFilter. Validation runs in Self::build.
ConversationMultiSelectElement
A menu for selecting multiple conversations.
ConversationMultiSelectElementBuilder
Consuming builder for ConversationMultiSelectElement. Validation runs in Self::build.
ConversationSelectElement
A menu for selecting one conversation.
ConversationSelectElementBuilder
Consuming builder for ConversationSelectElement. Validation runs in Self::build.
DataPoint
One value of a chart series, keyed by axis category.
DataPointBuilder
Consuming builder for DataPoint. Validation runs in Self::build.
DataSeries
A named series of chart data points.
DataSeriesBuilder
Consuming builder for DataSeries. Validation runs in Self::build.
DataTableBlock
A sortable, paginated table of raw text, numbers, and rich text.
DataTableBlockBuilder
Consuming builder for DataTableBlock. Validation runs in Self::build.
DataVisualizationBlock
A titled pie, bar, area, or line chart.
DataVisualizationBlockBuilder
Consuming builder for DataVisualizationBlock. Validation runs in Self::build.
DatePickerElement
A calendar date picker.
DatePickerElementBuilder
Consuming builder for DatePickerElement. Validation runs in Self::build.
DateTimePickerElement
A combined date and time picker.
DateTimePickerElementBuilder
Consuming builder for DateTimePickerElement. Validation runs in Self::build.
DispatchActionConfiguration
Chooses which interactions with an input send a block_actions payload.
DispatchActionConfigurationBuilder
Consuming builder for DispatchActionConfiguration. Validation runs in Self::build.
DividerBlock
A horizontal rule that separates blocks.
DividerBlockBuilder
Consuming builder for DividerBlock. Validation runs in Self::build.
EmailInputElement
A single-line input that accepts an email address.
EmailInputElementBuilder
Consuming builder for EmailInputElement. Validation runs in Self::build.
ExternalMultiSelectElement
A menu for selecting multiple options loaded from your app.
ExternalMultiSelectElementBuilder
Consuming builder for ExternalMultiSelectElement. Validation runs in Self::build.
ExternalSelectElement
A menu for selecting one option loaded from your app.
ExternalSelectElementBuilder
Consuming builder for ExternalSelectElement. Validation runs in Self::build.
FeedbackButton
One button of a feedback buttons element.
FeedbackButtonBuilder
Consuming builder for FeedbackButton. Validation runs in Self::build.
FeedbackButtonsElement
A pair of thumbs-up and thumbs-down feedback buttons.
FeedbackButtonsElementBuilder
Consuming builder for FeedbackButtonsElement. Validation runs in Self::build.
FileBlock
A retrieved remote-file representation. Register and share files through the files.remote API; Slack does not accept directly posting file blocks.
FileBlockBuilder
Consuming builder for FileBlock. Validation runs in Self::build.
FileInputElement
An input that lets users upload files.
FileInputElementBuilder
Consuming builder for FileInputElement. Validation runs in Self::build.
HeaderBlock
Large, bold plain text that introduces a group of blocks.
HeaderBlockBuilder
Consuming builder for HeaderBlock. Validation runs in Self::build.
HomeTabView
The payload for publishing an App Home tab with views.publish.
HomeTabViewBuilder
Consuming builder for HomeTabView. Validation runs in Self::build.
IconButtonElement
A button that shows an icon instead of text.
IconButtonElementBuilder
Consuming builder for IconButtonElement. Validation runs in Self::build.
ImageBlock
A standalone image with alternative text and an optional title.
ImageBlockBuilder
Consuming builder for ImageBlock. Validation runs in Self::build.
ImageElement
An image displayed inside a section, context, or card.
ImageElementBuilder
Consuming builder for ImageElement. Validation runs in Self::build.
InputBlock
A labelled input that collects a value in a modal, App Home, or message.
InputBlockBuilder
Consuming builder for InputBlock. Validation runs in Self::build.
InputParameter
A named value passed to a workflow trigger.
InputParameterBuilder
Consuming builder for InputParameter. Validation runs in Self::build.
JsonNumber
A JSON integer, unsigned integer, or finite floating-point number.
LayoutBlock
A visual grid of one to five rows on messages, modals, and App Home. Supply fallback content for older clients.
LayoutBlockBuilder
Consuming builder for LayoutBlock. Validation runs in Self::build.
LayoutItem
One supported child block with a proportional width and optional direction-aware alignment.
LayoutItemBuilder
Consuming builder for LayoutItem. Validation runs in Self::build.
LayoutRow
One to three layout items in reading order. A row has no alignment or discriminator.
LayoutRowBuilder
Consuming builder for LayoutRow. Validation runs in Self::build.
LineChart
A line chart for a data visualization block.
LineChartBuilder
Consuming builder for LineChart. Validation runs in Self::build.
MarkdownBlock
Standard markdown rendered by Slack, intended for AI-generated content.
MarkdownBlockBuilder
Consuming builder for MarkdownBlock. Validation runs in Self::build.
MarkdownText
A mrkdwn text composition object.
MarkdownTextBuilder
Consuming builder for MarkdownText. Validation runs in Self::build.
MessagePayload
A complete payload for chat.postMessage and related Web API methods.
MessagePayloadBuilder
Consuming builder for MessagePayload. Validation runs in Self::build.
MessageResponse
A response body for slash commands and interaction response URLs.
MessageResponseBuilder
Consuming builder for MessageResponse. Validation runs in Self::build.
ModalView
The view payload for views.open, views.push, and views.update.
ModalViewBuilder
Consuming builder for ModalView. Validation runs in Self::build.
NumberInputElement
An input that accepts whole or decimal numbers.
NumberInputElementBuilder
Consuming builder for NumberInputElement. Validation runs in Self::build.
OverflowElement
A compact menu of up to five options.
OverflowElementBuilder
Consuming builder for OverflowElement. Validation runs in Self::build.
Paginator
A validated page of blocks and its navigation controls.
PaginatorBuilder
Consuming configuration for a Paginator.
PieChart
A pie chart for a data visualization block.
PieChartBuilder
Consuming builder for PieChart. Validation runs in Self::build.
PlainText
A plain-text composition object.
PlainTextBuilder
Consuming builder for PlainText. Validation runs in Self::build.
PlainTextInput
A plain-text builder argument: either an owned string or validated plain text.
PlainTextInputElement
A single-line or multi-line free-text input.
PlainTextInputElementBuilder
Consuming builder for PlainTextInputElement. Validation runs in Self::build.
PlanBlock
A titled sequence of task cards.
PlanBlockBuilder
Consuming builder for PlanBlock. Validation runs in Self::build.
RadioButtonsElement
A group of radio buttons.
RadioButtonsElementBuilder
Consuming builder for RadioButtonsElement. Validation runs in Self::build.
RawNumber
A numeric table or data table cell with display text.
RawNumberBuilder
Consuming builder for RawNumber. Validation runs in Self::build.
RawText
An unformatted table cell.
RawTextBuilder
Consuming builder for RawText. Validation runs in Self::build.
RichTextBlock
Formatted text built from sections, lists, preformatted blocks, and quotes.
RichTextBlockBuilder
Consuming builder for RichTextBlock. Validation runs in Self::build.
RichTextChannel
A channel mention inside rich text.
RichTextChannelBuilder
Consuming builder for RichTextChannel. Validation runs in Self::build.
RichTextCodeBlock
A preformatted code block inside rich text.
RichTextCodeBlockBuilder
Consuming builder for RichTextCodeBlock. Validation runs in Self::build.
RichTextEmoji
An emoji inside rich text.
RichTextEmojiBuilder
Consuming builder for RichTextEmoji. Validation runs in Self::build.
RichTextInputElement
An input that accepts formatted rich text.
RichTextInputElementBuilder
Consuming builder for RichTextInputElement. Validation runs in Self::build.
RichTextLink
A hyperlink inside rich text.
RichTextLinkBuilder
Consuming builder for RichTextLink. Validation runs in Self::build.
RichTextList
A bulleted or numbered list inside rich text.
RichTextListBuilder
Consuming builder for RichTextList. Validation runs in Self::build.
RichTextQuote
A quotation inside rich text.
RichTextQuoteBuilder
Consuming builder for RichTextQuote. Validation runs in Self::build.
RichTextSection
A paragraph of inline rich text elements.
RichTextSectionBuilder
Consuming builder for RichTextSection. Validation runs in Self::build.
RichTextStyle
Optional rich-text style flags. Each receiving element validates its allowed subset.
RichTextText
A run of optionally styled text inside rich text.
RichTextTextBuilder
Consuming builder for RichTextText. Validation runs in Self::build.
RichTextUser
A user mention inside rich text.
RichTextUserBuilder
Consuming builder for RichTextUser. Validation runs in Self::build.
RichTextUserGroup
A user group mention inside rich text.
RichTextUserGroupBuilder
Consuming builder for RichTextUserGroup. Validation runs in Self::build.
SectionBlock
Text, a grid of fields, or both, with an optional accessory element.
SectionBlockBuilder
Consuming builder for SectionBlock. Validation runs in Self::build.
SelectOption
A selectable option for menus, checkboxes, radio buttons, and overflow menus.
SelectOptionBuilder
Consuming builder for SelectOption. Validation runs in Self::build.
SelectOptionGroup
A labelled group of options in a static select menu.
SelectOptionGroupBuilder
Consuming builder for SelectOptionGroup. Validation runs in Self::build.
SlackFile
A reference to an image file hosted in Slack.
SlackFileBuilder
Consuming builder for SlackFile. Validation runs in Self::build.
SlackIcon
A Slack-provided icon, referenced by name.
SlackIconBuilder
Consuming builder for SlackIcon. Validation runs in Self::build.
StaticMultiSelectElement
A menu for selecting multiple options defined in the payload.
StaticMultiSelectElementBuilder
Consuming builder for StaticMultiSelectElement. Validation runs in Self::build.
StaticSelectElement
A menu for selecting one option defined in the payload.
StaticSelectElementBuilder
Consuming builder for StaticSelectElement. Validation runs in Self::build.
TableBlock
A simple table of raw text, numeric and rich text cells. Cell text is limited to 10,000 Unicode code points per table and across tables in a message.
TableBlockBuilder
Consuming builder for TableBlock. Validation runs in Self::build.
TaskCardBlock
One task with its status, details, output, and sources.
TaskCardBlockBuilder
Consuming builder for TaskCardBlock. Validation runs in Self::build.
TextInput
A text builder argument. Strings use the receiving field’s documented text kind. There is deliberately no global string-to-Text conversion.
TimePickerElement
A time-of-day picker.
TimePickerElementBuilder
Consuming builder for TimePickerElement. Validation runs in Self::build.
Trigger
A link trigger that starts a workflow.
TriggerBuilder
Consuming builder for Trigger. Validation runs in Self::build.
UrlInputElement
A single-line input that accepts a URL.
UrlInputElementBuilder
Consuming builder for UrlInputElement. Validation runs in Self::build.
UrlSource
A linked source cited by a task card.
UrlSourceBuilder
Consuming builder for UrlSource. Validation runs in Self::build.
UserMultiSelectElement
A menu for selecting multiple workspace users.
UserMultiSelectElementBuilder
Consuming builder for UserMultiSelectElement. Validation runs in Self::build.
UserSelectElement
A menu for selecting one workspace user.
UserSelectElementBuilder
Consuming builder for UserSelectElement. Validation runs in Self::build.
ValidationError
A checked-construction or parsing error, with a full Slack wire-field path.
VideoBlock
An embedded video player.
VideoBlockBuilder
Consuming builder for VideoBlock. Validation runs in Self::build.
WebhookMessage
A payload for incoming webhooks.
WebhookMessageBuilder
Consuming builder for WebhookMessage. Validation runs in Self::build.
Workflow
The workflow started by a workflow button.
WorkflowBuilder
Consuming builder for Workflow. Validation runs in Self::build.
WorkflowButtonElement
A button that starts a workflow through a link trigger.
WorkflowButtonElementBuilder
Consuming builder for WorkflowButtonElement. Validation runs in Self::build.

Enums§

AlertLevel
Severity levels supported by alert blocks.
Block
A validated Slack layout block accepted directly by a JSON transport.
BuilderPayload
Borrowed input shapes for a Block Kit Builder preview URL.
ButtonStyle
Visual emphasis for buttons and confirmation dialogs.
Chart
A chart that can be displayed by a data visualization block.
ColumnAlign
Horizontal alignment for table columns.
ContainerWidth
Widths supported by Slack container blocks.
ContextActionsElement
A value that can appear in a context actions block: feedback buttons or an icon button.
ContextElement
A value that can appear in a context block: an image element or a text object.
DataTableCell
A value that can appear as a data table cell: raw text, a raw number, or a rich text block.
Element
A validated interactive, visual, or input element nested inside a Slack block.
ErrorCategory
The shared validation category; message wording is not a compatibility promise.
IconButtonIcon
Icons supported by icon buttons.
InputElement
An element that can be placed in an input block.
LayoutAlignment
Direction-aware alignment within a layout item. Omit for fill behavior.
LayoutChild
A block that can occupy a layout item; it must also be valid on the enclosing surface.
LayoutFallback
A stable block that older clients render in place of a layout.
LayoutGridLines
Layout borders: none, outer border with horizontal row dividers, or outer border only.
LayoutWidth
Relative layout item weights: narrow is 1, standard is 2, and wide is 3.
ResponseType
Visibility of a slash-command or interaction response.
RichTextBlockElement
A top-level element of a rich text block: a section, list, preformatted block, or quote.
RichTextListStyle
Marker styles for rich text lists.
RichTextSectionElement
An inline rich text element: text, a link, an emoji, or a channel, user, or user group mention.
TableCell
A value that can appear as a table block cell: raw text, a raw number, or a rich text block.
TaskStatus
States supported by task card blocks.
Text
A Slack text composition object: plain text or mrkdwn.

Constants§

SPEC_VERSION
Version of the shared Slack Block Kit contract.
VERSION
The Cargo package version; independent of the shared specification version.

Functions§

block_kit_builder_url
Creates a Slack Block Kit Builder URL without performing any network requests. Optional team IDs are encoded as a single path segment. JSON is encoded as UTF-8.