Post to Instagram, TikTok and Facebook from Python with one API
With easyCoexistence, Python code posts to Instagram, Facebook, TikTok, YouTube and LinkedIn through each network's official API. Each account signs in once through a hosted link; your script then fetches a fresh TikTok, YouTube or LinkedIn token with one GET, while Instagram and Facebook calls go through easyCoexistence's MCP tools, which keep the token. The MCP tools give a Python agent the same accounts.
The most text one Instagram DM can carry through the API, counted in UTF-8, so emoji take more room.
How long a TikTok API for Business access token lasts; its refresh token stays valid for a year.
How long a Google user access token, the kind every YouTube API call carries, stays valid.
The MCP Python SDK's OAuth handler, which registers the client, runs the sign-in with PKCE and refreshes tokens.
Forwarded comment, mention and DM events are delivered once and never stored, so acknowledge each one at once.
How does Python get a token for Instagram, Facebook, TikTok, YouTube or LinkedIn?
Through a connect session on easyCoexistence's Partner API, authenticated with your ec_live_ key. POST /connect-sessions with channel set to instagram, facebook, tiktok, youtube or linkedin returns a hosted link for one customer, valid for an hour. They sign in with the network's own login and land on your redirect_url with status=connected and a channel_id, which your backend confirms with GET /connect-sessions/{session} rather than trusting the query string. Your code never needs a developer app of its own on Meta, TikTok, Google or LinkedIn.
Then ask for credentials at the start of every job. GET /channels/{id}?credentials=1 returns the network's API base, the account's id on that network and, for TikTok, YouTube and LinkedIn, an access token that easyCoexistence keeps renewed. TikTok's token lasts 24 hours and Google's one hour, so fetch it per job instead of saving it. Instagram and Facebook tokens are never handed out; their calls go through the MCP tools.
import os
import requests
EC = "https://easycoexistence.com/api/v1"
KEY = {"Authorization": f"Bearer {os.environ['EC_API_KEY']}"} # ec_live_...
# A hosted sign-in link for one customer on one network
session = requests.post(f"{EC}/connect-sessions", headers=KEY, json={
"channel": "instagram", # or facebook, tiktok, youtube, linkedin
"redirect_url": "https://app.example.com/connected",
"external_ref": "customer_4821",
}).json()
print(session["url"]) # they come back with ?session=...&status=connected&channel_id=...
def credentials(channel_id: str) -> dict:
"""The network's API base and a token that is valid now. Call it per job."""
r = requests.get(f"{EC}/channels/{channel_id}", headers=KEY, params={"credentials": 1})
r.raise_for_status()
creds = r.json()["credentials"]
if not creds.get("access_token"):
raise RuntimeError(creds.get("note", "This channel is not connected."))
return credsHow do you post to Instagram and Facebook from Python?
Instagram publishes in two steps on Meta's Graph API, with the token as a bearer header. POST /{ig-id}/media with an image_url and a caption creates a container; once a GET of its status_code reads FINISHED, POST /{ig-id}/media_publish with the container as creation_id puts it on the profile. Meta suggests checking about once a minute, for up to five minutes. A Reel follows the same steps, sent with media_type REELS and a video_url instead of an image.
A Facebook Page post is one call: POST /{page-id}/feed with a message and, if you want one, a link. Adding published false and a scheduled_publish_time between 10 minutes and 30 days ahead makes Meta publish it at that moment, with no job of yours running. Meta downloads media from a public URL in both cases, and Instagram takes JPEG images only.
import time
import requests
def graph(c: dict, path: str, **body) -> dict:
"""Meta's Graph API: a POST when there is a body, a GET when there is none."""
r = requests.request("POST" if body else "GET", f"{c['graph_api_base']}/{path}",
json=body or None, headers={"Authorization": f"Bearer {c['access_token']}"})
r.raise_for_status()
return r.json()
def post_to_instagram(channel_id: str, image_url: str, caption: str) -> str:
c = credentials(channel_id)
ig = c["account_id_on_meta"]
container = graph(c, f"{ig}/media", image_url=image_url, caption=caption)["id"]
for _ in range(5): # Meta: check about once a minute, for up to five minutes
status = graph(c, f"{container}?fields=status_code")["status_code"]
if status == "FINISHED":
return graph(c, f"{ig}/media_publish", creation_id=container)["id"]
if status in ("ERROR", "EXPIRED"):
raise RuntimeError(f"Instagram could not process the media: {status}")
time.sleep(60)
raise TimeoutError("The container is still processing")
def schedule_on_facebook(channel_id: str, message: str, publish_at: int) -> str:
c = credentials(channel_id)
post = graph(c, f"{c['account_id_on_meta']}/feed", message=message,
published=False, scheduled_publish_time=publish_at) # unix seconds
return post["id"]How do you upload to YouTube and post on LinkedIn from Python?
YouTube takes the video as a resumable upload. The first request goes to the upload endpoint with uploadType=resumable and part=snippet,status and carries the title and status as JSON; the Location header of its answer is the session address. A PUT of the file to that address answers 201 with the new video. Setting privacyStatus to private with a publishAt time lets YouTube publish the video by itself at that moment, and selfDeclaredMadeForKids records whether it is made for children.
LinkedIn takes one POST to /rest/posts with the bearer token, a LinkedIn-Version header and X-Restli-Protocol-Version 2.0.0. The body names the author, carries the text as commentary and sets visibility, distribution and lifecycleState. The credentials supply author_urn, a urn:li:organization for a company Page or a urn:li:person for a profile, and the version easyCoexistence uses; the new post's URN comes back in the x-restli-id header.
import requests
def schedule_on_youtube(channel_id: str, path: str, title: str, publish_at: str) -> str:
c = credentials(channel_id)
auth = {"Authorization": f"Bearer {c['access_token']}"}
start = requests.post(
"https://www.googleapis.com/upload/youtube/v3/videos",
params={"uploadType": "resumable", "part": "snippet,status"},
headers={**auth, "X-Upload-Content-Type": "video/mp4"},
json={"snippet": {"title": title},
"status": {"privacyStatus": "private", "publishAt": publish_at, # ISO 8601
"selfDeclaredMadeForKids": False}},
)
start.raise_for_status()
with open(path, "rb") as video: # streamed, not read into memory
done = requests.put(start.headers["Location"], data=video,
headers={**auth, "Content-Type": "video/mp4"})
done.raise_for_status()
return done.json()["id"]
def post_on_linkedin(channel_id: str, text: str) -> str:
c = credentials(channel_id)
r = requests.post(f"{c['api_base']}/posts", headers={
"Authorization": f"Bearer {c['access_token']}",
"LinkedIn-Version": c["required_headers"]["LinkedIn-Version"], # YYYYMM
"X-Restli-Protocol-Version": "2.0.0",
}, json={
"author": c["author_urn"], # urn:li:organization:... or urn:li:person:...
"commentary": text,
"visibility": "PUBLIC",
"distribution": {"feedDistribution": "MAIN_FEED", "targetEntities": [],
"thirdPartyDistributionChannels": []},
"lifecycleState": "PUBLISHED",
"isReshareDisabledByAuthor": False,
})
r.raise_for_status()
return r.headers["x-restli-id"] # the new post's URNHow do you read and reply to comments and DMs in Python?
Turn on forwarding for the channel, verify every delivery, then reply through the network's API. PUT /channels/{id}/webhook with a url returns a signing_secret, shown only once. Comments, mentions and DMs on Instagram and Facebook, and comments on TikTok, then arrive as a POST of platform, account_id, external_id and entry, with entry exactly as the network sent it. The X-EC-Signature header reads t=<unix>,v1=<hex>, and v1 is an HMAC-SHA256 of the timestamp, a dot and the raw body. Each event is sent once, with no copy kept and no retry, so acknowledge first and work from a queue.
A reply to an Instagram DM goes to /{ig-id}/messages within 24 hours of the person's last message, in at most 1,000 bytes. A comment gets a public reply at /{comment-id}/replies, or one private reply within 7 days. TikTok comments get public replies through business/comment/reply/create/, because there are no DMs on TikTok, and YouTube and LinkedIn comments are read through their APIs on a schedule.
import hashlib, hmac, json, queue, time
import requests
from flask import Flask, abort, request
app = Flask(__name__)
jobs: queue.Queue = queue.Queue() # a worker calls reply_on_instagram() for each event
SECRETS: dict[str, str] = {} # channel_id -> signing_secret; keep them in your database
def forward_events(channel_id: str, url: str) -> None:
r = requests.put(f"{EC}/channels/{channel_id}/webhook", headers=KEY, json={"url": url})
r.raise_for_status()
SECRETS[channel_id] = r.json()["signing_secret"] # returned only this once
def verified(raw: bytes, header: str, secret: str) -> bool:
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
t, v1 = parts.get("t", ""), parts.get("v1", "")
if not t.isdigit() or abs(time.time() - int(t)) > 300:
return False
mac = hmac.new(secret.encode(), t.encode() + b"." + raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(mac.encode(), v1.encode())
@app.post("/hooks/social")
def social_event():
raw = request.get_data()
event = json.loads(raw) # platform, account_id, external_id, entry
secret = SECRETS.get(event.get("account_id"))
if not secret or not verified(raw, request.headers.get("X-EC-Signature", ""), secret):
abort(401)
jobs.put(event) # sent once and never retried: acknowledge first, work after
return "", 204
def reply_on_instagram(event: dict, text: str) -> None:
c, me = credentials(event["account_id"]), event["external_id"]
for m in event["entry"].get("messaging", []): # DMs, minus echoes of your own
if "message" in m and not m["message"].get("is_echo"):
graph(c, f"{me}/messages", recipient={"id": m["sender"]["id"]}, message={"text": text})
for ch in event["entry"].get("changes", []): # comments, minus your own replies
if ch["field"] == "comments" and ch["value"]["from"]["id"] != me:
graph(c, f"{ch['value']['id']}/replies", message=text)How do you post to TikTok from Python?
Through easyCoexistence's MCP tool publish_tiktok_post. TikTok's API for Business takes a video as a video_url and, since November 16, 2023, downloads it only from a domain or URL prefix verified for the developer app behind the token, which is easyCoexistence's. The tool takes your HTTPS link and hands TikTok a signed address on easyCoexistence's verified media route, streaming the file without storing it. Photo posts take image_urls instead, 1 to 35 JPEG or WebP files, and get_tiktok_publish_status follows the post while TikTok processes it.
From Python, that is one call through the official MCP SDK, version 2, on Python 3.10 or later. The server at https://easycoexistence.com/api/mcp accepts OAuth 2.1 only, so the SDK's OAuthClientProvider registers your client, runs one browser sign-in with PKCE and refreshes tokens. Access tokens last an hour and refresh tokens 60 days, each refresh issues a new pair, and storage that persists them keeps a backend signed in.
import asyncio
import os
from urllib.parse import parse_qs, urlparse
import httpx2
from pydantic import AnyUrl
from mcp import Client
from mcp.client.auth import AuthorizationCodeResult, OAuthClientProvider
from mcp.client.streamable_http import streamable_http_client
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
MCP_URL = "https://easycoexistence.com/api/mcp"
class Storage: # keep both values in a database, so the browser sign-in happens once
tokens: OAuthToken | None = None
client: OAuthClientInformationFull | None = None
async def get_tokens(self): return self.tokens
async def set_tokens(self, tokens): self.tokens = tokens
async def get_client_info(self): return self.client
async def set_client_info(self, info): self.client = info
async def show_sign_in(url: str) -> None:
print("Sign in to easyCoexistence:", url)
async def read_callback() -> AuthorizationCodeResult:
query = parse_qs(urlparse(input("Paste the address you were sent back to: ")).query)
return AuthorizationCodeResult(code=query["code"][0], state=query["state"][0])
oauth = OAuthClientProvider(
server_url=MCP_URL,
client_metadata=OAuthClientMetadata(
client_name="My social agent",
redirect_uris=[AnyUrl("http://localhost:3030/callback")],
scope="mcp",
),
storage=Storage(),
redirect_handler=show_sign_in,
callback_handler=read_callback,
)
async def main() -> None:
timeout = httpx2.Timeout(30.0, read=300.0)
async with httpx2.AsyncClient(auth=oauth, timeout=timeout) as http:
async with Client(streamable_http_client(MCP_URL, http_client=http)) as client:
result = await client.call_tool("publish_tiktok_post", {
"account_id": os.environ["TIKTOK_CHANNEL_ID"], # the Partner API channel id
"video_url": "https://cdn.example.com/launch.mp4",
"caption": "New drop #behindthescenes",
})
print(result.content[0].text) # a share_id for get_tiktok_publish_status
asyncio.run(main())How does a Python AI agent use these accounts?
Through the same MCP session. The server lists the tools for the networks on your account, and any agent framework that accepts MCP tools can hand them to its model: publish on each network, list posts, read comments and reply to them, reply to DMs on Instagram and Facebook, set comment-to-DM rules and read insights and analytics. The server's instructions and each tool's description carry the network's rules, so the model learns that TikTok replies are public and that Instagram images must be JPEG.
Start the agent with list_social_accounts, since every other social tool takes an account_id from it, and that id is the same channel id the Partner API returns. Replies that must go out at 3am with no agent running belong to comment rules and automations, which run on easyCoexistence itself.
Common mistakes
- Saving the token in a config file. TikTok's expires within a day and Google's within an hour, and easyCoexistence renews them behind the scenes, so call the credentials endpoint at the start of each job.
- Giving TikTok a link on your own domain. TikTok downloads media only from URL prefixes verified for the app that holds the token, so publish through publish_tiktok_post, which serves your file from easyCoexistence's verified address.
- Replying to each comment event, your own included. Your public replies come back as new comments and your Instagram DMs as echoes, so skip events whose author is the account itself, or the bot replies to itself.
- Measuring an Instagram DM in characters. The cap is 1,000 bytes of UTF-8, so text with emoji or accented letters runs out sooner; trim by encoded length before sending.
easyCoexistence gives your Python code and your AI agents reach to customers on WhatsApp, Instagram, Facebook, TikTok, YouTube, LinkedIn and more channels, through each network's official API. The Partner API connects accounts and hands out fresh tokens, the MCP server gives agents the same accounts as tools, and every connection is monitored 24/7. US$ 9 to US$ 0.75 per connection per month, falling as you add connections, with the first 3 days free.
easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.
Frequently asked questions
Do I need my own Meta, TikTok, Google or LinkedIn developer app?
No. Accounts sign in through easyCoexistence's own app on each network, and the credentials call hands your code the account's token on TikTok, YouTube and LinkedIn, ready to use against the network's API.
Which Python version and libraries do I need?
The Partner API and the networks' APIs are plain HTTPS with JSON, so requests, httpx or any other Python HTTP client calls them. The MCP Python SDK, version 2, which TikTok publishing and agent tools use, needs Python 3.10 or later.
Which networks send comments and DMs to my endpoint?
Instagram and Facebook forward comments, mentions and DMs, and TikTok forwards comments, each signed with the channel's secret. YouTube and LinkedIn send no such events, so read their comments through their APIs on a schedule.
How much does easyCoexistence cost for Python?
US$ 9 to US$ 0.75 per connection per month, falling as you add connections, and the same on every network. The Partner API and the MCP connector are included, with no seats, and the first 3 days are free.
Keep reading
Connect your first channel in two minutes.
No platform reviews to wait for. Connect WhatsApp, Instagram, TikTok or another channel, then ask your AI to post, reply or report, and watch it work.
- 3 days free
- Cancel any time
- Official APIs only
- Monitored 24/7
Verified on