Social Media API in Python: Working Examples (2026)
One Python client, 13 social platforms. No separate SDKs for each network. Here's the complete script from auth to analytics.

If you're searching "social media API Python," you already know what you need: a working script that posts to multiple platforms without a month of OAuth wrangling.
Key takeaways
- One unified API replaces a separate library per platform: install the official SDK with pip install omnisocials.
- The SDK needs Python 3.9 or newer and has one dependency, httpx.
- A post without a schedule time is saved as a draft; create_and_publish posts right away.
On this page
- Key takeaways
- How do you post to social media using Python?
- Why a Unified API Instead of Platform-Specific SDKs?
- Setup (2 minutes)
- Your First Post: X, LinkedIn, and Bluesky in 10 Lines
- Attaching Images
- Scheduling a Post
- Publishing Right Away
- Reading Analytics
- Error Handling for Production Scripts
- Async Code
- Prefer Plain requests?
- Complete Working Script
- Going Further
- Frequently Asked Questions
- How do you post to social media using Python?
- Is there a Python library for social media APIs?
- Can Python automate Instagram posts?
- Sources
This guide gives you that. One API, one Python client, 13 platforms. By the end, you'll have a complete script that schedules content, attaches images, publishes right away, and reads analytics.
How do you post to social media using Python?
The fastest approach: use a unified social media API. Sign up for OmniSocials, connect your social accounts, create an API key, and install the official Python SDK with pip install omnisocials. Then one client.posts.create() call with a channels list posts to Instagram, LinkedIn, X, Bluesky, TikTok, or all of them at once. No per-platform SDK, no separate OAuth flow for each network. The OmniSocials Python SDK page has the full reference.
Why a Unified API Instead of Platform-Specific SDKs?
The alternative is installing and maintaining a separate library for each platform:
- Tweepy for X (Twitter)
- python-linkedin or linkedin-api for LinkedIn
- instagrapi for Instagram (unofficial, breaks regularly with Instagram updates)
- TikTok doesn't have a stable Python SDK
- Bluesky uses AT Protocol (atproto library)
Each library has different authentication models, different rate limit handling, and different maintenance states. When Instagram changes their API (they do, regularly), your instagrapi integration breaks.
A unified API like OmniSocials handles the platform-specific complexity on their end. You write one integration, and it doesn't break when Instagram updates their API.
Setup (2 minutes)
Install the SDK:
pip install omnisocials
The package is MIT licensed, needs Python 3.9 or newer, and its only dependency is httpx.
Get your API key:
- Sign up at omnisocials.com
- Connect your social accounts via the dashboard (Instagram, LinkedIn, etc. Each takes about 2 minutes via OAuth)
- Go to Settings > API
- Click Create API Key, pick the scopes you need, and copy the key (it starts with
omsk_live_and is shown only once) - Store it as an environment variable:
export OMNISOCIALS_API_KEY="omsk_live_your_key_here"
The client reads OMNISOCIALS_API_KEY on its own. If you keep it in a .env file, load it with python-dotenv before creating the client:
from dotenv import load_dotenv
from omnisocials import OmniSocials
load_dotenv()
client = OmniSocials() # reads OMNISOCIALS_API_KEY
There are no test keys. Every key posts to your real connected accounts, so use drafts (leave out scheduled_at) while you experiment.
Your First Post: X, LinkedIn, and Bluesky in 10 Lines
from omnisocials import OmniSocials
client = OmniSocials() # reads OMNISOCIALS_API_KEY
post = client.posts.create(
content="Just published a new Python tutorial. Link in the replies.",
channels=["x", "linkedin", "bluesky"],
scheduled_at="2027-03-02T09:00:00Z",
)
print(post["data"]["id"], post["data"]["status"]) # 1019 scheduled
Responses come back as plain dicts wrapped in a data key, so the new post is post["data"].
The channels list accepts any combination of: instagram, facebook, linkedin (profile), linkedin_page, x, tiktok, youtube, pinterest, bluesky, threads, mastodon, google_business. Use x, not twitter. Instagram and TikTok posts need at least one image or video (next section), and YouTube takes vertical videos posted as Shorts. Every channel you list has to be connected to the workspace your key belongs to, otherwise the API answers 400 with platform_not_connected.
Attaching Images
The quickest way to attach an image is media_urls. OmniSocials downloads the file from the URL and stores it with the post:
post = client.posts.create(
content="New article is live. Here's the key takeaway.",
channels=["instagram", "linkedin"],
media_urls=["https://your-cdn.com/your-image.jpg"],
scheduled_at="2027-03-02T09:00:00Z",
)
If you want to reuse a file across posts, upload it to your media library first and pass its id:
image = client.media.upload_from_url(
url="https://your-cdn.com/your-image.jpg",
)
client.posts.create(
content="New article is live. Here's the key takeaway.",
channels=["instagram", "linkedin"],
media_ids=[image["data"]["id"]],
scheduled_at="2027-03-02T09:00:00Z",
)
For a file on disk, use client.media.upload(file="./banner.jpg") instead. Direct uploads go up to 100 MB, and upload_from_url handles files up to 1 GB. Accepted formats are JPEG, PNG, GIF, WebP, HEIC (converted to JPEG), MP4, MOV, AVI, and PDF (split into image slides for carousels).
Scheduling a Post
scheduled_at takes an ISO 8601 timestamp, and it has to be in the future. Leave it out and the post is saved as a draft.
from datetime import datetime, timedelta, timezone
# Tomorrow at 09:00 UTC
tomorrow_9am = (datetime.now(timezone.utc) + timedelta(days=1)).replace(
hour=9, minute=0, second=0, microsecond=0
)
post = client.posts.create(
content="Dropping something new tomorrow. Stay tuned.",
channels=["linkedin", "x"],
scheduled_at=tomorrow_9am.isoformat(),
)
print(post["data"]["id"], post["data"]["status"]) # ... scheduled
Publishing Right Away
To skip the schedule and publish now, use create_and_publish. It takes the same arguments as create, minus scheduled_at:
post = client.posts.create_and_publish(
content="We're live. The new docs are up.",
channels=["linkedin", "bluesky"],
)
print(post["data"]["status"]) # posting
The post starts as posting and moves to published once every platform has answered (warning when some platforms failed, failed when all did). Check it later with client.posts.get(post_id), or let a webhook tell you.
Reading Analytics
stats = client.analytics.post("1019") # the OmniSocials post id
linkedin = stats["data"]["platforms"].get("linkedin")
if linkedin:
print(linkedin["metrics"])
Each connected platform reports its own metrics under platforms, so the keys differ between LinkedIn, Instagram, and the rest.
For workspace-level numbers and posting-time advice:
overview = client.analytics.overview(period="30d")
print(overview["data"]["total_impressions"])
best = client.analytics.best_times(platform="linkedin")
print(best["recommendations"]) # top 3: day, time, score
Note that best_times is the one call without the data wrapper: recommendations sits at the top level of the response.
Error Handling for Production Scripts
The SDK already retries the failures that are worth retrying: 429, 5xx responses, and network errors, twice by default, and it waits for the Retry-After header when the API sends one. What's left for you is deciding what to do when a request is really rejected:
from omnisocials import (
AuthenticationError,
OmniSocials,
RateLimitError,
ValidationError,
)
client = OmniSocials(max_retries=5, timeout=60.0)
try:
client.posts.create(
content="Weekly update is live.",
channels=["linkedin", "mastodon"],
scheduled_at="2027-03-05T16:00:00Z",
)
except AuthenticationError:
print("API key invalid or revoked. Check OMNISOCIALS_API_KEY.")
except ValidationError as err:
print(err.code, err.message) # e.g. platform_not_connected
except RateLimitError as err:
print(f"Rate limited, retry in {err.retry_after}s")
Common status codes:
400: Validation error (text too long for a platform, missing field, a channel that isn't connected).err.codesays which.401: Missing or invalid API key403: The key lacks the scope for this call (for exampleposts:write)429: Rate limit exceeded. The limit is 100 requests per minute per API key.5xx: Something went wrong on the OmniSocials side. The SDK retries these for you.
Async Code
If your script already runs on asyncio (a FastAPI app, a bot, an agent), use AsyncOmniSocials. Every resource and method has the same name, you just await it:
import asyncio
from omnisocials import AsyncOmniSocials
async def main():
async with AsyncOmniSocials() as client:
scheduled = await client.posts.list(status="scheduled")
print(len(scheduled["data"]), "posts in the queue")
asyncio.run(main())
Prefer Plain requests?
The SDK is a thin layer over a REST API, so you can call it with any HTTP client. This is the same scheduled post with requests:
import os
import requests
response = requests.post(
"https://api.omnisocials.com/v1/posts",
headers={"Authorization": f"Bearer {os.environ['OMNISOCIALS_API_KEY']}"},
json={
"content": "Just published a new Python tutorial.",
"channels": ["x", "linkedin", "bluesky"],
"scheduled_at": "2027-03-02T09:00:00Z",
},
timeout=30,
)
response.raise_for_status()
print(response.json()["data"]["id"])
You lose the automatic retries and typed exceptions, so for anything beyond a quick test the SDK is less code.
Complete Working Script
Copy-paste ready:
"""
OmniSocials Python posting script
https://omnisocials.com/sdk/python
Install: pip install omnisocials
Setup: export OMNISOCIALS_API_KEY="omsk_live_..."
"""
from datetime import datetime, timedelta, timezone
from omnisocials import OmniSocials, ValidationError
client = OmniSocials() # reads OMNISOCIALS_API_KEY
def schedule(channels, text, publish_at, image_url=None):
"""Schedule a post for a future date and time."""
return client.posts.create(
content=text,
channels=channels,
scheduled_at=publish_at.isoformat(),
media_urls=[image_url] if image_url else None,
)["data"]
def publish_now(channels, text, image_url=None):
"""Publish a post immediately."""
return client.posts.create_and_publish(
content=text,
channels=channels,
media_urls=[image_url] if image_url else None,
)["data"]
if __name__ == "__main__":
tomorrow = (datetime.now(timezone.utc) + timedelta(days=1)).replace(
hour=9, minute=0, second=0, microsecond=0
)
try:
post = schedule(
["bluesky", "mastodon"],
"Scheduled post via Python and the OmniSocials SDK.",
tomorrow,
)
print(f"Scheduled: {post['id']} ({post['status']})")
live = publish_now(
["linkedin", "x"],
"Testing the OmniSocials Python integration. Works great.",
)
print(f"Publishing: {live['id']} ({live['status']})")
except ValidationError as err:
print(f"Rejected: {err.code}: {err.message}")
Going Further
The SDK isn't Python-only. The same API has official clients for Node.js, Go, Rust, .NET, Java, PHP, and Ruby, all listed on the OmniSocials SDK overview.
For building AI agents that use social media as an action layer, see our social media API for developers guide. It covers the full API surface, including webhooks, analytics endpoints, and multi-account management.
If you're posting to Instagram specifically, the post to Instagram API guide covers media requirements, carousel posts, and Reels. For X, the Twitter API in Python guide covers threads, media limits, and link posts.
OmniSocials offers a single flat-rate API that covers every platform with no per-network fees, unlike stitching together native platform APIs or paying a per-post reseller.
Get your API key. Sign up for OmniSocials →. $10/month (billed annually), 13 platforms, API access included in the plan.
Frequently Asked Questions
How do you post to social media using Python?
The fastest approach: use a unified social media API. Sign up for OmniSocials, connect your accounts, create an API key, and install the official SDK with pip install omnisocials. Call client.posts.create() with content, a channels list, and scheduled_at. One call posts to Instagram, LinkedIn, X, Bluesky, and more at the same time.
Is there a Python library for social media APIs?
There are per-platform libraries (Tweepy for X, instagrapi for Instagram), but each requires separate maintenance and breaks when platforms update their APIs. OmniSocials has an official, MIT-licensed Python SDK (pip install omnisocials) with a sync OmniSocials client and an async AsyncOmniSocials client. One client covers 13 platforms.
Can Python automate Instagram posts?
Yes, via the OmniSocials API. Connect Instagram to your OmniSocials account once via OAuth, then use the Python SDK to post images, carousels, and Reels. You don't need to deal with Instagram's Graph API or Meta's app review process directly.
Sources
- OmniSocials Python SDK: Install, quickstart, and the full method list
- OmniSocials API Documentation: Full API reference
- Instagram Graph API: Native API reference (complex path)
- Tweepy Documentation: X (Twitter) Python SDK (per-platform alternative)
Try OmniSocials for 14 days
Plan, schedule and answer on 13 platforms from one calendar, or let your AI agent do it. The first charge comes when the trial ends.


