Post to social media from Python with Ampost
By ArturPublished Updated
The Ampost Python SDK publishes a post to every network you name with one call, so a Python script needs no per-network OAuth. Install the SDK, download the script below, set AMPOST_API_KEY, and run it with your text and networks. A version that uses only the standard library is there too.
What you'll build
- A command-line script that publishes a text, link, image or video post to several social networks at once, now or at a scheduled time.
- The same call in your own code: a Django or Flask app, a data pipeline, a cron job or an AI agent.
Before you start
- An Ampost account. The Free plan includes the REST API (2 social accounts and 15 posts every 30 days); scheduling needs the Pro plan or higher, and X the Max and Scale plans. See pricing.
- An API key from Settings, API keys. The key is shown once, so copy it when you create it. Treat it like a password.
- At least one connected social account, under Settings, Connections in the dashboard.
- Python 3.9 or later for the SDK. The standard-library script needs no packages and runs on Python 3.8.
Download
Free to use and change. The file is shown in full below, so you can read it before you run it.
#!/usr/bin/env python3
"""Post to social media with the Ampost Python SDK.
One call publishes (or schedules) a post on every network you name:
Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and
Discord. Python 3.9+ and the `ampost` package:
pip install git+https://github.com/ampost-io/ampost-python
export AMPOST_API_KEY=amp_live_...
python post_with_sdk.py --text "Hello from Python" --platforms bluesky,threads
python post_with_sdk.py --text "New post" --platforms threads --link https://example.com/post
python post_with_sdk.py --text "Launch" --platforms instagram,threads --media launch.jpg
python post_with_sdk.py --text "Tomorrow" --platforms bluesky --schedule 2027-01-14T15:00:00Z
Guide: https://ampost.io/how-to/post-to-social-media-from-python
SDK: https://ampost.io/docs/tools/python-sdk
"""
import argparse
import sys
from ampost import Ampost, AmpostError
def build_body(client, args):
platforms = [p.strip() for p in args.platforms.split(",") if p.strip()]
if not platforms:
raise SystemExit("--platforms needs at least one platform, for example bluesky,threads")
body = {"targets": [{"platforms": platforms}], "text": args.text}
if args.link:
body["linkUrl"] = args.link
if args.media:
# A public https URL is fetched by Ampost; a local file is uploaded first.
if args.media.startswith("https://"):
body["media"] = [{"url": args.media, "type": args.media_type}]
else:
body["media"] = [client.media.upload(args.media)]
if args.schedule:
body["scheduledFor"] = args.schedule
else:
body["publishNow"] = True
return body
def main(argv=None):
parser = argparse.ArgumentParser(description="Post to social media with the Ampost Python SDK.")
parser.add_argument("--text", required=True, help="the post text")
parser.add_argument(
"--platforms",
required=True,
help="comma-separated: instagram, facebook, threads, twitter, youtube, pinterest, bluesky, telegram, discord",
)
parser.add_argument("--link", help="a link to attach (linkUrl)")
parser.add_argument("--media", help="an image or video: a local file or a public https URL")
parser.add_argument("--media-type", choices=["image", "video"], default="image", help="the type of a --media URL")
parser.add_argument("--schedule", help="publish later, at this ISO 8601 time, e.g. 2027-01-14T15:00:00Z")
parser.add_argument("--idempotency-key", help="reuse a key to make re-runs safe (default: one per run)")
args = parser.parse_args(argv)
# The client reads AMPOST_API_KEY. It retries rate limits and server errors with the same
# Idempotency-Key, so a retried request never posts twice.
try:
with Ampost() as client:
post = client.posts.create(build_body(client, args), idempotency_key=args.idempotency_key)
except AmpostError as error:
# API errors read "400 VALIDATION_FAILED: ...": the status, Ampost's code and its message.
print("Could not post: %s" % error, file=sys.stderr)
return 1
print("Post %s is %s" % (post["id"], post["status"]))
for platform_post in post["platformPosts"]:
print(" %s: %s %s" % (platform_post["platform"], platform_post["status"], platform_post.get("publishedUrl") or ""))
return 0
if __name__ == "__main__":
sys.exit(main())
#!/usr/bin/env python3
"""Post to social media with the Ampost API.
One request publishes (or schedules) a post on every network you name:
Instagram, Facebook, LinkedIn, TikTok, Threads, X, Discord, Telegram, Bluesky,
YouTube and Pinterest. Python 3.8+, standard library only.
export AMPOST_API_KEY=amp_live_...
python post_to_social.py --text "Hello from Python" --platforms bluesky,threads
python post_to_social.py --text "New post" --platforms threads --link https://example.com/post
python post_to_social.py --text "Launch" --platforms instagram \
--media-url https://example.com/launch.jpg --media-type image
python post_to_social.py --text "Tomorrow" --platforms facebook --schedule 2027-01-14T15:00:00Z
Guide: https://ampost.io/how-to/post-to-social-media-from-python
API reference: https://ampost.io/docs
"""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
API_URL = os.environ.get("AMPOST_API_URL", "https://api.ampost.io").rstrip("/")
# Retry rate limits (429 RATE_LIMITED) and server errors (5xx) this many times. The
# Idempotency-Key header makes a retry safe: Ampost never posts twice.
MAX_ATTEMPTS = 4
def create_post(api_key, body, idempotency_key=None):
"""POST /api/posts and return the created post as a dict.
Raises RuntimeError with Ampost's error code and message when the request fails.
"""
key = idempotency_key or str(uuid.uuid4())
data = json.dumps(body).encode("utf-8")
for attempt in range(1, MAX_ATTEMPTS + 1):
request = urllib.request.Request(
API_URL + "/api/posts",
data=data,
method="POST",
headers={
"Authorization": "Bearer " + api_key,
"Content-Type": "application/json",
"Idempotency-Key": key,
"User-Agent": "ampost-python-template/1.0",
},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
status = error.code
payload = error.read().decode("utf-8", "replace")
# QUOTA_EXCEEDED is a 429 too, but it lasts until the plan's 30-day window frees up.
retryable = (status == 429 and "QUOTA_EXCEEDED" not in payload) or status >= 500
if retryable and attempt < MAX_ATTEMPTS:
time.sleep(_retry_delay(error.headers.get("Retry-After"), attempt))
continue
raise RuntimeError(_describe_error(status, payload)) from None
except urllib.error.URLError as error:
if attempt < MAX_ATTEMPTS:
time.sleep(_retry_delay(None, attempt))
continue
raise RuntimeError("Could not reach %s: %s" % (API_URL, error.reason)) from None
raise RuntimeError("unreachable")
def _retry_delay(retry_after, attempt):
try:
return min(float(retry_after), 60.0)
except (TypeError, ValueError):
return float(2 ** attempt)
def _describe_error(status, payload):
try:
error = json.loads(payload)["error"]
return "%s %s: %s" % (status, error.get("code"), error.get("message"))
except (ValueError, KeyError, TypeError):
return "%s: %s" % (status, payload[:500])
def build_body(args):
platforms = [p.strip() for p in args.platforms.split(",") if p.strip()]
if not platforms:
raise SystemExit("--platforms needs at least one platform, for example bluesky,threads")
body = {"targets": [{"platforms": platforms}], "text": args.text}
if args.link:
body["linkUrl"] = args.link
if args.media_url:
body["media"] = [{"url": args.media_url, "type": args.media_type}]
if args.schedule:
body["scheduledFor"] = args.schedule
else:
body["publishNow"] = True
return body
def main(argv=None):
parser = argparse.ArgumentParser(description="Post to social media with the Ampost API.")
parser.add_argument("--text", required=True, help="the post text")
parser.add_argument(
"--platforms",
required=True,
help="comma-separated: instagram, facebook, linkedin, tiktok, threads, twitter, "
"discord, telegram, bluesky, youtube, pinterest",
)
parser.add_argument("--link", help="a link to attach (linkUrl)")
parser.add_argument("--media-url", help="a public https URL of an image or video")
parser.add_argument("--media-type", choices=["image", "video"], default="image")
parser.add_argument("--schedule", help="publish later, at this ISO 8601 time, e.g. 2027-01-14T15:00:00Z")
parser.add_argument("--idempotency-key", help="reuse a key to make re-runs safe (default: random)")
args = parser.parse_args(argv)
api_key = os.environ.get("AMPOST_API_KEY")
if not api_key:
raise SystemExit("Set AMPOST_API_KEY to an API key from https://ampost.io/app/settings/api-keys")
try:
post = create_post(api_key, build_body(args), args.idempotency_key)
except RuntimeError as error:
print("Ampost refused the post: %s" % error, file=sys.stderr)
return 1
print("Post %s is %s" % (post["id"], post["status"]))
for result in post.get("platformPosts", []):
print(" %-10s %-11s %s" % (result["platform"], result["status"], result.get("publishedUrl") or ""))
return 0
if __name__ == "__main__":
sys.exit(main())
Steps
1. Install the SDK
The SDK is coming to PyPI as
ampost. Until then, install it from GitHub; a virtual environment keeps it out of your system Python.terminalpython3 -m venv .venv && . .venv/bin/activate pip install git+https://github.com/ampost-io/ampost-python2. Download the script and set your key
Download
post_with_sdk.pyabove and put your API key in theAMPOST_API_KEYenvironment variable, where the SDK reads it. Keep the key out of your code and out of git.terminalexport AMPOST_API_KEY=amp_live_your_key_here3. Publish a post
Run the script with the text and a comma-separated list of networks. Platform keys:
instagram(Instagram),facebook(Facebook),linkedin(LinkedIn),tiktok(TikTok),threads(Threads),twitter(X),discord(Discord),telegram(Telegram),bluesky(Bluesky),youtube(YouTube),pinterest(Pinterest).It prints the new post's id and status, then one line per account.
terminalpython3 post_with_sdk.py --text "Hello from Python and Ampost!" --platforms bluesky,threads4. Add a link, an image or a schedule
--linkattaches a link and--schedulepublishes later instead of now.--mediatakes a local image or video, which the SDK uploads first, or a public https URL (with--media-type imageorvideo) that Ampost fetches; either way Ampost fits it to each network.Posting clips from a video or clipping tool? Video and clipping tools lists the Reels and Shorts options and each network's video limits.
terminalpython3 post_with_sdk.py --text "New article" --platforms threads,bluesky --link https://example.com/post python3 post_with_sdk.py --text "Launch day" --platforms instagram,facebook --media launch.jpg python3 post_with_sdk.py --text "See you tomorrow" --platforms bluesky --schedule 2027-01-14T15:00:00Z5. Call it from your own code
client.posts.create(body)returns the post as a dict. The body is the API's JSON; pass your ownidempotency_key(for example your record's id) so a second run of a job never posts twice.app.pyfrom ampost import Ampost with Ampost() as client: # reads AMPOST_API_KEY post = client.posts.create( {"targets": [{"platforms": ["bluesky", "threads"]}], "text": "Shipped v2.0!", "publishNow": True}, idempotency_key="release-2.0", ) print(post["id"], post["status"])
How errors are handled
The SDK retries RATE_LIMITED and server errors, waiting for the Retry-After header, and sends the same Idempotency-Key each time: a request that reached Ampost before a timeout is never posted twice.
Other errors raise a typed exception with Ampost's code and message, for example BadRequestError with VALIDATION_FAILED, or PermissionDeniedError with UPGRADE_REQUIRED when your plan lacks a feature. The script prints them as Could not post: .... The codes are in the API reference.
Without the SDK
post_to_social.py does the same with the standard library only: copy it into a project that can't add packages. create_post(api_key, body) sends POST https://api.ampost.io/api/posts, retries like the SDK and returns the post as a dict. It takes --media-url for a public https file instead of --media.
If your project already uses requests, the whole call is a few lines:
import os, uuid, requests
response = requests.post(
"https://api.ampost.io/api/posts",
headers={
"Authorization": f"Bearer {os.environ['AMPOST_API_KEY']}",
"Idempotency-Key": str(uuid.uuid4()),
},
json={"targets": [{"platforms": ["bluesky", "threads"]}], "text": "Hello!", "publishNow": True},
timeout=60,
)
response.raise_for_status()
print(response.json()["id"])FAQ
Is there an Ampost Python SDK?
Yes. It has sync and async clients, typed models for every endpoint, retries and a one-call media upload. It is coming to PyPI as ampost; until then, install it with pip from github.com/ampost-io/ampost-python.
Do I need a developer account on each social network?
No. You connect each account to Ampost once in the dashboard, and the script only needs your Ampost API key.
Which social networks can I post to from Python?
Every network you connect to Ampost: Instagram, Facebook, LinkedIn, TikTok, Threads, X, Discord, Telegram, Bluesky, YouTube, Pinterest. Name them by key in targets[].platforms; X is twitter. LinkedIn and TikTok are coming soon.
Can I schedule a post instead of publishing it now?
Yes. Send scheduledFor with an ISO 8601 time (for example 2027-01-14T15:00:00Z) instead of publishNow: true, and Ampost publishes it then. Scheduling needs the Pro plan or higher.
What happens if the same request is sent twice?
The templates send an Idempotency-Key header. A retry with the same key within 24 hours returns the first post instead of creating a second one, so a retried step never posts twice.