Developers
Posting to Mastodon via the API: Statuses, Media, Idempotency-Key and scheduled_at
· 7 min read
Post to Mastodon via the API: registering an app per instance, POST /api/v1/statuses, async media uploads, Idempotency-Key, scheduled_at, content warnings and limits.
To post to Mastodon via the API, send `POST /api/v1/statuses` to the user's own instance with a bearer token that has the `write:statuses` scope and a `status` field containing the text. Attach media by uploading it first to POST /api/v2/media and passing the returned ids as media_ids[]. Send an Idempotency-Key header so a retried request can't create a duplicate post. To schedule natively, add scheduled_at at least 5 minutes in the future and Mastodon returns a ScheduledStatus instead of a Status. The big difference from other networks: there's no single Mastodon API host. Every instance is its own server, and you register your app on each one.
Step 1: register your app on the instance
Mastodon OAuth starts with a client id and secret, and those are per instance. The first time a user from mastodon.social connects, you register with mastodon.social. The first user from hachyderm.io triggers a registration there. Store the credentials keyed by normalized instance URL (lowercase, no trailing slash) and reuse them for every later user from that server.
curl -X POST "https://mastodon.social/api/v1/apps" \
-H "Content-Type: application/json" \
-d '{
"client_name": "My Scheduler",
"redirect_uris": "https://app.example.com/oauth/mastodon/callback",
"scopes": "read write",
"website": "https://app.example.com"
}'
# {"client_id": "...", "client_secret": "...", ...}Then send the user to https://{instance}/oauth/authorize with your client id, redirect URI and scopes, and exchange the returned code at /oauth/token. Request the narrowest scopes you need. write:statuses and write:media are enough to post with images, plus read:accounts to look up the profile. Mastodon tokens don't expire by default, so there's no refresh dance. They live until the user revokes them.
Encrypt the stored client secrets and tokens. A table of instance credentials is a quiet but valuable target.
Step 2: post a status
curl -X POST "https://mastodon.social/api/v1/statuses" \
-H "Authorization: Bearer $MASTODON_TOKEN" \
-H "Idempotency-Key: 4f1c2a9e0b7d4c33a1e6f0b8d2c5e7a9" \
-H "Content-Type: application/json" \
-d '{
"status": "New release: v2.4 adds CSV export. Changelog at https://example.com/changelog #OpenSource",
"visibility": "public",
"language": "en"
}'
# {"id": "113555...", "url": "https://mastodon.social/@you/113555...", "content": "<p>New release...</p>", ...}Useful optional fields: visibility (public, unlisted, private for followers only, direct), spoiler_text for a content warning, sensitive to blur media, language as an ISO 639-1 code, and in_reply_to_id to reply. The response's content is HTML, not your original text, so don't round-trip it into an editor without converting it back.
Idempotency-Key: do this from day one
Networks drop connections. If your request reaches Mastodon, the status gets created, and the response never makes it back, a naive retry posts the same thing twice. Mastodon supports an Idempotency-Key header: send the same key on the retry and you get the original status back instead of a new one. Keys are stored for up to one hour, which comfortably covers any sane retry schedule.
A bug we shipped and fixed: we built the key by concatenating the account id and the post text. Post text has emoji, accented letters and newlines. HTTP header values can't carry those, and fetch rejects the request before it's ever sent. It surfaced as a generic network error, our worker retried it three times, and each time it failed the same way. Hash the identity instead. A hex digest is always header-safe.
async function idempotencyKey(accountId: string, replyTo: string | null, text: string) {
const identity = accountId + ":" + (replyTo ?? "root") + ":" + text
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity))
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")
}Include the reply target in the identity. Otherwise a thread where two replies have the same text ("Thanks!") collapses into one post.
Step 3: media uploads are asynchronous
Upload with POST /api/v2/media as multipart, with the file and an optional description, which is the alt text. Small images usually come back 200 with a url, ready to use. Video and large images come back 202 Accepted with url: null, meaning the server is still processing. A status can only attach a finished attachment, so poll GET /api/v1/media/:id. It returns 206 Partial Content while processing and 200 when done.
async function uploadMedia(instance: string, token: string, file: Blob, name: string, alt: string) {
const form = new FormData()
form.set("file", file, name)
form.set("description", alt)
const res = await fetch(instance + "/api/v2/media", {
method: "POST",
headers: { Authorization: "Bearer " + token },
body: form,
})
if (!res.ok && res.status !== 202) throw new Error("Upload failed: " + res.status)
const media = await res.json()
for (let i = 0; !media.url && i < 30; i++) {
await new Promise((r) => setTimeout(r, 2000))
const poll = await fetch(instance + "/api/v1/media/" + media.id, {
headers: { Authorization: "Bearer " + token },
})
if (poll.status === 200) return (await poll.json()).id
}
if (!media.url) throw new Error("Media still processing after 60s")
return media.id
}Write alt text. On Mastodon it isn't optional in practice: many people won't boost an image without a description, and some instances' moderators notice. Our guide to Mastodon content warnings, hashtags and alt text covers the etiquette.
Limits come from the instance, not the docs
Mastodon's defaults are 500 characters and 4 attachments, but admins change them, and forks like Glitch or Hometown often raise them. Read the real values from GET /api/v2/instance and validate against those.
| Field in /api/v2/instance | Mastodon default / example | Use it for |
|---|---|---|
| configuration.statuses.max_characters | 500 | Text length check |
| configuration.statuses.max_media_attachments | 4 | Attachment count |
| configuration.statuses.characters_reserved_per_url | 23 | Every URL counts as 23 characters |
| configuration.media_attachments.image_size_limit | 16,777,216 bytes in the docs example | Image size check |
| configuration.media_attachments.video_size_limit | 103,809,024 bytes in the docs example | Video size check |
| configuration.media_attachments.description_limit | 1,500 in the docs example | Alt text length |
| configuration.media_attachments.supported_mime_types | List | Reject unsupported files before upload |
The URL rule matters for length checks: a 90-character tracking link costs 23 characters, not 90. Count the way the instance does or you'll reject valid posts. Also, don't mix video with images in one status. Mastodon won't accept it. Our Mastodon character counter applies the 23-character link rule.
scheduled_at: native scheduling
Add scheduled_at (ISO 8601, at least 5 minutes ahead) and Mastodon stores the post and publishes it itself. The response is a ScheduledStatus with its own id. List pending ones with GET /api/v1/scheduled_statuses, reschedule with PUT /api/v1/scheduled_statuses/:id, cancel with DELETE. A time in the past returns 422 with "The scheduled date must be in the future."
Should you use it? For one account and one-off posts, yes, it means nothing on your side has to wake up. For a scheduling product, we prefer keeping the schedule ourselves and posting at the time. Edits stay in one place, posts across several networks go out together, and an instance that's down at publish time is a retry rather than a silent miss. The Mastodon scheduling guide compares both approaches for non-developers.
Rate limits and errors
| Limit (default, per Mastodon docs) | Value |
|---|---|
| All endpoints, per account | 300 requests / 5 minutes |
| All endpoints, per IP | 300 requests / 5 minutes |
| Media uploads (POST /api/v1/media) | 30 / 30 minutes |
| Deleting statuses or unboosting | 30 / 30 minutes |
Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset for the limit you're closest to hitting. The per-IP limit is the one that catches schedulers: if your workers post for many accounts on the same instance from one IP, they share 300 requests per 5 minutes. Spread the load and read the headers.
- 401 / 403: token revoked or missing a scope. Don't retry. Ask the user to reconnect.
- 422: validation failed (too long, too many attachments, media still processing). Fix, don't retry.
- 429: wait until
X-RateLimit-Reset. - 5xx or timeout: retry with the same Idempotency-Key. That's exactly what it's for.
- Instance unreachable: small instances go down. Retry over minutes, not seconds, and tell the user if it lasts.
Threads on Mastodon
A thread is a chain of statuses where each one's in_reply_to_id is the previous status's id. Post the first, read its id, post the next as a reply. Use unlisted visibility for replies after the first if you don't want each one filling followers' home timelines. Hashtags work best in CamelCase (#OpenSource, not #opensource) so screen readers pronounce them properly.
When to use a scheduling API instead of building it yourself
Mastodon's API is pleasant: no review, no fees, tokens that don't expire. The work is in the federation details: per-instance app registration, async media, per-instance limits, idempotency, and instances that come and go. Worth building if Mastodon is your main network. Less so if it's one of six.
Tesselith posts to Mastodon on any instance today, through the app or the REST API, with idempotent retries handled. Our scheduling API checklist and the automation walkthrough cover the trade-offs, and the docs show the requests.
Questions people ask
- How do I post a status with the Mastodon API?
- Send POST /api/v1/statuses to the user's instance with a bearer token that has write:statuses and a status field with the text. Attach media by uploading to /api/v2/media first and passing media_ids[].
- Does the Mastodon API support scheduling?
- Yes. Add scheduled_at with an ISO 8601 time at least 5 minutes in the future. Mastodon returns a ScheduledStatus and publishes it at that time.
- What does the Idempotency-Key header do on Mastodon?
- It prevents duplicate posts when a request is retried. Mastodon stores the key for up to one hour and returns the original status for repeats.
- What is the Mastodon API rate limit?
- By default, 300 requests per 5 minutes per account and per IP, and 30 media uploads per 30 minutes. Instances can change these.
- Why does my Mastodon post fail with media attached?
- The attachment may still be processing. /api/v2/media returns 202 for large files; poll GET /api/v1/media/:id until it returns 200 before posting.