Apex Connect Api Chatter
Activate this skill when Apex needs to post to Chatter, reply to a feed item, or @mention a user programmatically. The ConnectApi namespace is the only supported way to produce rich-content posts (mentions, links, files, polls) — direct DML on FeedItem is limited and does NOT support mention rendering.
Before Starting
Gather this context before working on anything in this domain:
- Is Chatter enabled in the org?
ConnectApi throws ConnectApi.ConnectApiException if disabled.
- What's the execution context?
ConnectApi has strict restrictions in @future and test methods.
- What sort of post? Plain text, text-with-mentions, link, file attachment, poll, or announcement?
- Who's the author? Running user by default; can impersonate only via
ConnectApi.ChatterFeeds.postFeedElement parameters in limited cases.
Core Concepts
ConnectApi vs Direct DML On FeedItem
insert new FeedItem(...) works but produces plain text only. No mentions, no files, no polls.
ConnectApi.ChatterFeeds.postFeedElement(...) supports the full post capability set (mentions, files, links, polls, announcements).
- Rule: if the post has any rich content, use ConnectApi. Use direct DML only for the simplest text post where capabilities are not needed.
FeedItemInput + MessageBodyInput + MessageSegmentInput
Rich posts are assembled from segments:
TextSegmentInput — plain text
MentionSegmentInput — @user or @group
LinkSegmentInput — inline URL
HashtagSegmentInput — #topic
Segments are concatenated in order into a MessageBodyInput, which is wrapped in a FeedItemInput.
Test Context Restrictions
ConnectApi methods throw in synchronous test methods unless Test.setMock(ConnectApi.ConnectApi.class, mock) or the SeeAllData=true annotation is used.
SeeAllData=true is a code-smell in most orgs; prefer the mock framework.
@future methods CAN call ConnectApi, but the calls run as the user who enqueued (or the automated user in some contexts) — test this explicitly.
Feed Parent Id Types
Feeds hang off a parent record. Common parent types:
- User Ids (
005...) — user's personal feed
- Group Ids (
0F9...) — Chatter group
- Record Ids (
001... etc.) — any object with feed tracking enabled
'me' — shorthand for the running user
Common Patterns
Plain-Text Post With @Mention
When to use: A trigger or service needs to notify an owner by @mentioning them in a record feed.
How it works:
public static void postMentionToRecord(Id recordId, Id userToMention, String message) {
ConnectApi.FeedItemInput post = new ConnectApi.FeedItemInput();
ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();
body.messageSegments = new List<ConnectApi.MessageSegmentInput>();
ConnectApi.MentionSegmentInput mention = new ConnectApi.MentionSegmentInput();
mention.id = userToMention;
body.messageSegments.add(mention);
ConnectApi.TextSegmentInput text = new ConnectApi.TextSegmentInput();
text.text = ' ' + message;
body.messageSegments.add(text);
post.body = body;
ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), recordId, post);
}
Why not the alternative: insert new FeedItem(Body='@Jane ...') shows literal @Jane text — no notification fires, no link is rendered.
Post With File Attachment
When to use: Uploading a report PDF and posting it to a record feed in one go.
How it works:
ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();
body.messageSegments = new List<ConnectApi.MessageSegmentInput>{
new ConnectApi.TextSegmentInput()
};
((ConnectApi.TextSegmentInput) body.messageSegments[0]).text = 'See attached report.';
input.body = body;
ConnectApi.NewFileAttachmentInput file = new ConnectApi.NewFileAttachmentInput();
file.title = 'Weekly Report';
input.capabilities = new ConnectApi.FeedElementCapabilitiesInput();
input.capabilities.content = new ConnectApi.ContentCapabilityInput();
input.capabilities.content.title = file.title;
ConnectApi.BinaryInput binary = new ConnectApi.BinaryInput(
Blob.valueOf(pdfBytes), 'application/pdf', 'report.pdf');
ConnectApi.ChatterFeeds.postFeedElement(
Network.getNetworkId(), recordId, input, binary);
Decision Guidance
| Situation |
Recommended Approach |
Reason |
| Plain text post, no mentions |
Either ConnectApi or DML |
Choose by team convention |
| Text with @mention |
ConnectApi MentionSegmentInput |
DML produces literal text |
| Post + file attachment |
ConnectApi with BinaryInput |
No DML equivalent |
| Poll post |
ConnectApi PollCapabilityInput |
No DML equivalent |
| Scheduled reminder post |
Queueable calling ConnectApi |
Governor-safe |
| Bulk posts (100s) |
Batch + ConnectApi per record |
Respects limits per execution |
| Experience Cloud posts |
Network.getNetworkId() arg |
null posts to internal Chatter |
Recommended Workflow
- Confirm Chatter is enabled — feature check via
FeatureManagement or an admin confirm.
- Identify feed parent — user, group, or record with feed tracking enabled.
- Build the
FeedItemInput by assembling message segments; handle null/empty text explicitly.
- Decide sync vs async — post in the current transaction unless you need isolation; if async, write a governor-bounded Queueable.
- Write tests —
Test.setMock(ConnectApi.ConnectApi.class, ...) to avoid real feed writes; assert the payload shape.
- Test Experience Cloud separately if posts must appear in a partner/customer community —
Network.getNetworkId() argument matters.
Review Checklist
Salesforce-Specific Gotchas
- Chatter off means ConnectApiException — orgs with Chatter disabled throw on every call; feature-flag the code.
FeedItem DML cannot render mentions — @Jane appears as literal text, no notification fires.
ConnectApi in test requires mocks — SeeAllData=false (the default) blocks real Chatter calls; use Test.setMock or the call throws.
- Network Id must be passed — omitting or using the wrong community Id posts to the wrong feed silently.
- Mentions require feed visibility — user must have access to the parent record; otherwise the mention is rendered but no notification fires.
- Feed tracking must be on — posting to a record whose object lacks feed tracking fails with a specific ConnectApiException.
- Polls cannot be edited after posting — only deleted and reposted.
- ConnectApi does NOT call triggers on FeedItem —
FeedItem triggers fire on DML, but ConnectApi writes go through a separate path; relying on FeedItem triggers for ConnectApi posts is unreliable.
Data 360 ConnectApi data graph reads (Spring '25–Spring '26)
Chatter is the primary ConnectApi surface for this skill, but teams mixing Data 360 data graphs into Apex should know the ConnectApi.CdpQuery additions (check each method's documented API version):
| Method family |
API version |
Use |
getDataGraphData(..., live) |
63.0 (Spring '25) |
Live/real-time data graph reads |
getDataGraphDataWithLookupKeys(..., noCache) |
64.0 (Summer '25) |
Lookup-key reads that bypass cache |
getMetadataEntities() (+ overloads with dataspace) |
66.0 (Spring '26) |
Discover graph entity metadata |
Earlier APIs expose materialized-view reads only. Version-gate call sites on apiVersion, not org release calendar.
Output Artifacts
| Artifact |
Description |
scripts/check_apex_connect_api_chatter.py |
Scans for literal @ mentions in FeedItem DML, missing ConnectApi mocks in tests, and unsafe error handling |
templates/apex-connect-api-chatter-template.md |
Work template for assembling FeedItemInput with mentions and attachments |
Related Skills
apex-custom-notifications-from-apex — bell notifications (different system from Chatter)
apex-email-messaging — email outreach (Chatter is not email)
apex-blob-and-content-version — managing files attached to Chatter posts
1---2name: apex-connect-api-chatter3description: "Use when posting to a Chatter feed, creating feed comments, @mentioning users or groups, or rendering rich-text posts from Apex via the ConnectApi namespace. Trigger keywords: ConnectApi, FeedItem, Chatter post, @mention, rich text post, FeedElementCapabilities, link post. NOT for Experience Cloud feed embeds. NOT for sending email from Apex — use apex/apex-outbound-email-patterns. NOT for custom bell notifications — use apex/apex-custom-notifications-from-apex. NOT for turning down org-wide Chatter feed and digest noise — use admin/chatter-notification-tuning."4category: apex5salesforce-version: "Spring '25+"6well-architected-pillars:7 - Security8 - Reliability9triggers:10 - "How do I post a Chatter comment with a file attachment from Apex?"11 - "I want to @mention a user in a FeedItem I'm creating from a trigger"12 - "My ConnectApi.ChatterFeeds.postFeedElement call works in UI tests but fails in @future context"13tags:14 - apex-connect-api-chatter15 - apex-chatter-posting16 - apex-connectapi17 - apex-mentions18inputs:19 - "Feed parent Id (record, user, group) being posted to"20 - "Post payload: text, mentions, links, file attachment"21 - "Execution context (sync, trigger, async)"22outputs:23 - "ConnectApi-based Chatter post implementation"24 - "Checker findings against unsupported async usage and unsafe input"25dependencies: []26version: 1.0.027author: Pranav Nagrecha28updated: 2026-04-2329metadata:30 source: https://skillmd.com/skills/pranavnagrecha/apex-connect-api-chatter31---3233# Apex Connect Api Chatter3435Activate this skill when Apex needs to post to Chatter, reply to a feed item, or @mention a user programmatically. The `ConnectApi` namespace is the only supported way to produce rich-content posts (mentions, links, files, polls) — direct DML on `FeedItem` is limited and does NOT support mention rendering.3637---3839## Before Starting4041Gather this context before working on anything in this domain:4243- Is Chatter enabled in the org? `ConnectApi` throws `ConnectApi.ConnectApiException` if disabled.44- What's the execution context? `ConnectApi` has strict restrictions in `@future` and test methods.45- What sort of post? Plain text, text-with-mentions, link, file attachment, poll, or announcement?46- Who's the author? Running user by default; can impersonate only via `ConnectApi.ChatterFeeds.postFeedElement` parameters in limited cases.4748---4950## Core Concepts5152### ConnectApi vs Direct DML On FeedItem5354- `insert new FeedItem(...)` works but produces plain text only. No mentions, no files, no polls.55- `ConnectApi.ChatterFeeds.postFeedElement(...)` supports the full post capability set (mentions, files, links, polls, announcements).56- Rule: if the post has any rich content, use ConnectApi. Use direct DML only for the simplest text post where capabilities are not needed.5758### `FeedItemInput` + `MessageBodyInput` + `MessageSegmentInput`5960Rich posts are assembled from segments:6162- `TextSegmentInput` — plain text63- `MentionSegmentInput` — `@user` or `@group`64- `LinkSegmentInput` — inline URL65- `HashtagSegmentInput` — `#topic`6667Segments are concatenated in order into a `MessageBodyInput`, which is wrapped in a `FeedItemInput`.6869### Test Context Restrictions7071- `ConnectApi` methods throw in synchronous test methods unless `Test.setMock(ConnectApi.ConnectApi.class, mock)` or the `SeeAllData=true` annotation is used.72- `SeeAllData=true` is a code-smell in most orgs; prefer the mock framework.73- `@future` methods CAN call `ConnectApi`, but the calls run as the user who enqueued (or the automated user in some contexts) — test this explicitly.7475### Feed Parent Id Types7677Feeds hang off a parent record. Common parent types:7879- User Ids (`005...`) — user's personal feed80- Group Ids (`0F9...`) — Chatter group81- Record Ids (`001...` etc.) — any object with feed tracking enabled82- `'me'` — shorthand for the running user8384---8586## Common Patterns8788### Plain-Text Post With @Mention8990**When to use:** A trigger or service needs to notify an owner by @mentioning them in a record feed.9192**How it works:**9394```apex95public static void postMentionToRecord(Id recordId, Id userToMention, String message) {96 ConnectApi.FeedItemInput post = new ConnectApi.FeedItemInput();97 ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();98 body.messageSegments = new List<ConnectApi.MessageSegmentInput>();99100 ConnectApi.MentionSegmentInput mention = new ConnectApi.MentionSegmentInput();101 mention.id = userToMention;102 body.messageSegments.add(mention);103104 ConnectApi.TextSegmentInput text = new ConnectApi.TextSegmentInput();105 text.text = ' ' + message;106 body.messageSegments.add(text);107108 post.body = body;109110 ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), recordId, post);111}112```113114**Why not the alternative:** `insert new FeedItem(Body='@Jane ...')` shows literal `@Jane` text — no notification fires, no link is rendered.115116### Post With File Attachment117118**When to use:** Uploading a report PDF and posting it to a record feed in one go.119120**How it works:**121122```apex123ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();124ConnectApi.MessageBodyInput body = new ConnectApi.MessageBodyInput();125body.messageSegments = new List<ConnectApi.MessageSegmentInput>{126 new ConnectApi.TextSegmentInput()127};128((ConnectApi.TextSegmentInput) body.messageSegments[0]).text = 'See attached report.';129input.body = body;130131ConnectApi.NewFileAttachmentInput file = new ConnectApi.NewFileAttachmentInput();132file.title = 'Weekly Report';133input.capabilities = new ConnectApi.FeedElementCapabilitiesInput();134input.capabilities.content = new ConnectApi.ContentCapabilityInput();135input.capabilities.content.title = file.title;136137ConnectApi.BinaryInput binary = new ConnectApi.BinaryInput(138 Blob.valueOf(pdfBytes), 'application/pdf', 'report.pdf');139140ConnectApi.ChatterFeeds.postFeedElement(141 Network.getNetworkId(), recordId, input, binary);142```143144---145146## Decision Guidance147148| Situation | Recommended Approach | Reason |149|---|---|---|150| Plain text post, no mentions | Either ConnectApi or DML | Choose by team convention |151| Text with @mention | ConnectApi `MentionSegmentInput` | DML produces literal text |152| Post + file attachment | ConnectApi with `BinaryInput` | No DML equivalent |153| Poll post | ConnectApi `PollCapabilityInput` | No DML equivalent |154| Scheduled reminder post | Queueable calling ConnectApi | Governor-safe |155| Bulk posts (100s) | Batch + ConnectApi per record | Respects limits per execution |156| Experience Cloud posts | `Network.getNetworkId()` arg | `null` posts to internal Chatter |157158---159160## Recommended Workflow1611621. Confirm Chatter is enabled — feature check via `FeatureManagement` or an admin confirm.1632. Identify feed parent — user, group, or record with feed tracking enabled.1643. Build the `FeedItemInput` by assembling message segments; handle null/empty text explicitly.1654. Decide sync vs async — post in the current transaction unless you need isolation; if async, write a governor-bounded Queueable.1665. Write tests — `Test.setMock(ConnectApi.ConnectApi.class, ...)` to avoid real feed writes; assert the payload shape.1676. Test Experience Cloud separately if posts must appear in a partner/customer community — `Network.getNetworkId()` argument matters.168169---170171## Review Checklist172173- [ ] No literal `@username` strings in FeedItem.Body — mentions are always `MentionSegmentInput`.174- [ ] `Network.getNetworkId()` (not hardcoded network Id) for community context.175- [ ] Tests use `Test.setMock(ConnectApi.ConnectApi.class, ...)`.176- [ ] ConnectApi call wrapped in try/catch of `ConnectApi.ConnectApiException`.177- [ ] Messages under Chatter's 10,000 char soft limit.178- [ ] File attachments under 2GB / org-specific limit.179180---181182## Salesforce-Specific Gotchas1831841. **Chatter off means ConnectApiException** — orgs with Chatter disabled throw on every call; feature-flag the code.1852. **`FeedItem` DML cannot render mentions** — `@Jane` appears as literal text, no notification fires.1863. **`ConnectApi` in test requires mocks** — `SeeAllData=false` (the default) blocks real Chatter calls; use `Test.setMock` or the call throws.1874. **Network Id must be passed** — omitting or using the wrong community Id posts to the wrong feed silently.1885. **Mentions require feed visibility** — user must have access to the parent record; otherwise the mention is rendered but no notification fires.1896. **Feed tracking must be on** — posting to a record whose object lacks feed tracking fails with a specific ConnectApiException.1907. **Polls cannot be edited after posting** — only deleted and reposted.1918. **ConnectApi does NOT call triggers on FeedItem** — `FeedItem` triggers fire on DML, but ConnectApi writes go through a separate path; relying on FeedItem triggers for ConnectApi posts is unreliable.192193---194195## Data 360 ConnectApi data graph reads (Spring '25–Spring '26)196197Chatter is the primary ConnectApi surface for this skill, but teams mixing **Data 360 data graphs** into Apex should know the **`ConnectApi.CdpQuery`** additions (check each method's documented API version):198199| Method family | API version | Use |200|---|---|---|201| `getDataGraphData(..., live)` | 63.0 (Spring '25) | Live/real-time data graph reads |202| `getDataGraphDataWithLookupKeys(..., noCache)` | 64.0 (Summer '25) | Lookup-key reads that bypass cache |203| `getMetadataEntities()` (+ overloads with dataspace) | 66.0 (Spring '26) | Discover graph entity metadata |204205Earlier APIs expose materialized-view reads only. Version-gate call sites on **`apiVersion`**, not org release calendar.206207---208209## Output Artifacts210211| Artifact | Description |212|---|---|213| `scripts/check_apex_connect_api_chatter.py` | Scans for literal `@` mentions in FeedItem DML, missing ConnectApi mocks in tests, and unsafe error handling |214| `templates/apex-connect-api-chatter-template.md` | Work template for assembling FeedItemInput with mentions and attachments |215216---217218## Related Skills219220- `apex-custom-notifications-from-apex` — bell notifications (different system from Chatter)221- `apex-email-messaging` — email outreach (Chatter is not email)222- `apex-blob-and-content-version` — managing files attached to Chatter posts