Engineering

Post to Instagram, LinkedIn and X with Python

Publish with Python requests using the native Instagram, LinkedIn, and X APIs, then build the same workflow through one Outstand integration.

Post to Instagram, LinkedIn and X with Python

You can use the Instagram API with Python to create a media container and publish it, LinkedIn's Posts API to publish text, and X API v2 to create a post. Each accepts HTTP requests, but authentication and payloads differ. Below are native requests examples, followed by a shared Outstand workflow for posting to all three accounts, scheduling delivery, and reading results.

TL;DR

  • Native APIs work well when you want direct control over each platform integration.
  • Instagram publishing requires media and an eligible professional account, not just a caption.
  • LinkedIn requires versioned headers; X posting requires user-context authentication.
  • Outstand provides one publishing contract, but X still requires your own developer credentials and API access.
  • A successful create request is not proof that every destination published. Check per-account outcomes.

This tutorial uses requests, not an invented Outstand Python SDK. The repository's SDK documentation covers a UI SDK, so ordinary HTTP is the documented path here.

Part 1: Native social media APIs with Python

Start with a virtual environment:

bash
1python -m venv .venv
2source .venv/bin/activate
3python -m pip install requests

The native snippets assume you have already completed each platform's authorization flow. An environment variable holds the resulting token; setting a variable does not obtain permissions or complete OAuth.

Platform

Publishing request

Prerequisite

Media behavior

Instagram

Create container, then publish

Professional account and publishing permission

Publicly accessible image for this example

LinkedIn

POST /rest/posts

Authorized member or organization author

Text works without an upload

X

POST /2/tweets

User token with write scope and funded access

Text works without an upload

Instagram API Python example: container, then publish

Meta's content publishing documentation describes a two-step flow: create a container with /{ig-user-id}/media, then publish that container with /{ig-user-id}/media_publish.

This example specifically uses Instagram API with Facebook Login, on graph.facebook.com. It requires a professional Instagram account linked to a Facebook Page and an appropriately authorized token. The documented permissions include instagram_basic, instagram_content_publish, and pages_read_engagement; additional requirements can depend on how Page access was granted.

Do not mix this route's token and permissions with Instagram Login's graph.instagram.com integration. They are separate login configurations.

Set META_GRAPH_VERSION to a supported version configured for your app, INSTAGRAM_ACCOUNT_ID to the Instagram professional account ID, and INSTAGRAM_IMAGE_URL to a public JPEG URL. A local filesystem path will not work because Meta fetches the image remotely.

python
1import os
2import requests
3
4base = (
5    "https://graph.facebook.com/"
6    f"{os.environ['META_GRAPH_VERSION']}/"
7    f"{os.environ['INSTAGRAM_ACCOUNT_ID']}"
8)
9headers = {
10    "Authorization": f"Bearer {os.environ['INSTAGRAM_ACCESS_TOKEN']}"
11}
12
13response = requests.post(
14    f"{base}/media",
15    headers=headers,
16    json={
17        "image_url": os.environ["INSTAGRAM_IMAGE_URL"],
18        "caption": "Our Python integration is live.",
19    },
20    timeout=30,
21)
22response.raise_for_status()
23container_id = response.json()["id"]
24
25response = requests.post(
26    f"{base}/media_publish",
27    headers=headers,
28    json={"creation_id": container_id},
29    timeout=30,
30)
31response.raise_for_status()
32print("Instagram media:", response.json()["id"])

This is a single-image example, not a general video publisher. For asynchronous media processing, add container-status checks before publishing rather than treating container creation as readiness. Our Instagram Graph API guide covers the wider integration.

Unofficial libraries such as instagrapi use private mobile and public web flows rather than this official publishing integration. That can carry Terms of Use and account-restriction or ban risk when access is unauthorized. Instagram's Terms of Use prohibit unauthorized automated access. This is not a claim that every library user is banned, but it is a different risk profile for customer accounts.

LinkedIn API Python example: versioned Posts API

LinkedIn's Posts API uses https://api.linkedin.com/rest/posts. It requires LinkedIn-Version and X-Restli-Protocol-Version headers.

Use w_member_social for an authenticated member, or w_organization_social with the required organization role for a company Page. Set LINKEDIN_AUTHOR_URN to the authorized author, such as a member or organization URN obtained through the relevant LinkedIn account-discovery flow.

python
1response = requests.post(
2    "https://api.linkedin.com/rest/posts",
3    headers={
4        "Authorization": f"Bearer {os.environ['LINKEDIN_ACCESS_TOKEN']}",
5        "LinkedIn-Version": "202611",
6        "X-Restli-Protocol-Version": "2.0.0",
7    },
8    json={
9        "author": os.environ["LINKEDIN_AUTHOR_URN"],
10        "commentary": "Our Python integration is live.",
11        "visibility": "PUBLIC",
12        "distribution": {
13            "feedDistribution": "MAIN_FEED",
14            "targetEntities": [],
15            "thirdPartyDistributionChannels": [],
16        },
17        "lifecycleState": "PUBLISHED",
18        "isReshareDisabledByAuthor": False,
19    },
20    timeout=30,
21)
22response.raise_for_status()
23print("LinkedIn post:", response.headers.get("x-restli-id"))

The 202611 value follows LinkedIn's November 2026 version documentation. Pin a supported version and plan upgrades, rather than omitting the header or copying an old tutorial indefinitely. See our LinkedIn Posts API walkthrough for the broader implementation.

Twitter API Python example: X API v2 user context

The endpoint is still named POST /2/tweets, even though the product is X. Its create-post reference accepts OAuth 2.0 user tokens with tweet.read, tweet.write, and users.read.

Obtain the token through OAuth 2.0 Authorization Code with PKCE. An app-only bearer token is not a posting credential. Request offline.access if your integration needs refresh tokens for background publishing.

python
1response = requests.post(
2    "https://api.x.com/2/tweets",
3    headers={
4        "Authorization": f"Bearer {os.environ['X_USER_ACCESS_TOKEN']}"
5    },
6    json={"text": "Our Python integration is live."},
7    timeout=30,
8)
9response.raise_for_status()
10print("X post:", response.json()["data"]["id"])

Pricing correction for older tutorials: as checked in November 2026, X's official pricing describes prepaid pay-per-usage access, not self-serve Free, Basic, and Pro subscriptions. It lists $0.015 per standard post creation and $0.200 for a post containing a URL. Enterprise access is separate. Check the console before budgeting; our X API pricing guide explains the model.

These three snippets publish independently. A native scheduler also needs durable jobs, token maintenance, platform-specific uploads, outcome storage, and separate analytics integrations. The HTTP call is the small part.

Part 2: How Outstand fits

Outstand keeps the same Python HTTP client but replaces three publishing payloads with one. Instagram and LinkedIn offer Managed Keys, so you can use Outstand's OAuth apps. X is BYOK: register your own X app, configure its credentials in Outstand, and maintain the required X API funding. Outstand does not remove X's platform charges or policies.

Start with Getting started. Create an API key on the server and load it from the environment:

bash
1export OUTSTAND_API_KEY="YOUR_API_KEY"
2export OUTSTAND_ORG_ID="YOUR_ORGANIZATION_ID"

Do not commit these values. In production, inject them through your deployment's secret manager.

1. Connect and select the accounts

Connecting requires user consent in a browser. Generate these URLs in Python, then send the user to the appropriate one:

python
1from urllib.parse import urlencode
2
3org_id = os.environ["OUTSTAND_ORG_ID"]
4query = urlencode({"redirect_uri": "https://yourapp.com/callback"})
5for network in ("instagram", "linkedin", "x"):
6    print(
7        f"https://www.outstand.so/app/api/socials/{network}/"
8        f"{org_id}?{query}"
9    )

The callback contracts differ. Instagram and X return success, account_id, network_unique_id, and username. LinkedIn returns a session token, and you must complete the documented account-selection/finalization flow before its account exists. Handle callback error values too. Do not treat a LinkedIn session token as an account ID.

For a first script, complete connections in the dashboard, then list the connected accounts. The following helper is reused throughout the remaining examples:

python
1BASE_URL = "https://api.outstand.so"
2AUTH = {"Authorization": f"Bearer {os.environ['OUTSTAND_API_KEY']}"}
3
4def api(method, path, **kwargs):
5    try:
6        response = requests.request(
7            method, f"{BASE_URL}{path}",
8            headers=AUTH, timeout=30, **kwargs,
9        )
10        response.raise_for_status()
11    except requests.HTTPError as exc:
12        raise RuntimeError(
13            f"Outstand returned HTTP {exc.response.status_code}; "
14            "inspect the response securely before retrying"
15        ) from exc
16    except requests.RequestException as exc:
17        raise RuntimeError(
18            "Transport failed; reconcile state before retrying a write"
19        ) from exc
20    return response.json()
21
22accounts = api("GET", "/v1/social-accounts")["data"]
23for account in accounts:
24    print(account["id"], account["network"], account["username"])

Save the three intended account IDs as OUTSTAND_INSTAGRAM_ACCOUNT_ID, OUTSTAND_LINKEDIN_ACCOUNT_ID, and OUTSTAND_X_ACCOUNT_ID. Choose explicitly if you have multiple accounts. Network names and account nicknames are not valid substitutes for IDs.

2. Upload the shared image

Because Instagram needs media, this cross-platform example attaches launch.jpg. Request an upload URL, PUT the raw bytes, then confirm the size. The confirmation response supplies the public URL used in the post.

python
1from pathlib import Path
2
3image = Path("launch.jpg")
4upload = api(
5    "POST", "/v1/media/upload",
6    json={"filename": image.name, "content_type": "image/jpeg"},
7)["data"]
8
9with image.open("rb") as stream:
10    response = requests.put(
11        upload["upload_url"],
12        headers={"Content-Type": "image/jpeg"},
13        data=stream,
14        timeout=120,
15    )
16response.raise_for_status()
17
18media = api(
19    "POST", f"/v1/media/{upload['id']}/confirm",
20    json={"size": image.stat().st_size},
21)

The PUT goes to storage, not the REST API. Do not attach the Outstand bearer token to that request. Use the confirmed url, not the upload ID or the temporary signed URL, in the publishing payload.

3. Create a post for all three accounts

This example schedules the image post one hour ahead. Omit scheduledAt to publish immediately instead; do not run both versions unless you want two posts.

python
1from datetime import datetime, timedelta, timezone
2
3account_ids = [
4    os.environ["OUTSTAND_INSTAGRAM_ACCOUNT_ID"],
5    os.environ["OUTSTAND_LINKEDIN_ACCOUNT_ID"],
6    os.environ["OUTSTAND_X_ACCOUNT_ID"],
7]
8known_ids = {account["id"] for account in accounts}
9if not set(account_ids).issubset(known_ids):
10    raise ValueError("Select connected account IDs from the listing")
11
12payload = {
13    "accounts": account_ids,
14    "containers": [{
15        "content": "Our Python integration is live.",
16        "media": [{"url": media["url"], "filename": image.name}],
17    }],
18    "scheduledAt": (
19        datetime.now(timezone.utc) + timedelta(hours=1)
20    ).isoformat(),
21}
22post = api("POST", "/v1/posts/", json=payload)["post"]
23post_id = post["id"]
24resolved = {account["id"] for account in post["socialAccounts"]}
25if resolved != set(account_ids):
26    raise RuntimeError("Created post has unexpected destinations; reconcile it")
27print("Queued:", post_id, post["scheduledAt"])

The response check matters: Outstand can silently discard an unresolvable account identifier if another identifier resolves. Persist post_id immediately so an application restart does not lose track of the job.

Scheduling accepts a future ISO 8601 timestamp up to 30 days ahead. Keep longer-horizon calendar entries in your own database until they enter that window. Use top-level instagram, linkedin, or x configuration objects for network-specific content overrides, rather than inventing a platforms wrapper.

4. Check delivery, then read analytics

Run this after the scheduled time. In a service, use bounded background polling, not a web request that sleeps for an hour:

python
1result = api("GET", f"/v1/posts/{post_id}")["post"]
2for account in result["socialAccounts"]:
3    print(
4        account["network"], account["status"],
5        account.get("platformPostId"), account.get("error"),
6    )
7
8if any(a["status"] == "published" for a in result["socialAccounts"]):
9    analytics = api("GET", f"/v1/posts/{post_id}/analytics")
10    print(analytics)

Per-account status can be pending, published, failed, or deleted. A successful Instagram destination does not prove LinkedIn or X succeeded. Retry only failed destinations after diagnosis, not the original three-account request.

Analytics requires a published post; drafts and scheduled posts return 400. The response includes per-account metrics and aggregated totals, with network-specific values under platform_specific. Preserve null values and inspect metrics_error when present. Missing measurements are not measured zeros, and aggregates can be partial.

Error handling before production

Keep transport errors, request rejection, and asynchronous delivery failures separate. raise_for_status() catches HTTP errors, not a later per-account failed outcome.

  • For 400 responses, fix the payload or unsupported media before retrying.
  • For authentication or permission errors, check the API key, granted permissions, and account connection.
  • For rate limiting, respect server retry guidance and use bounded backoff.
  • For a timed-out create request, reconcile stored state before resubmitting; the server may already have accepted it.
  • Keep credentials, signed upload URLs, and callback sessions out of routine logs.

Provision the key with the permissions needed for account access, media upload, post creation/publishing, and analytics. A key's presence alone does not grant every operation. For the larger architecture, read the practical social posting API guide.

FAQ

Can I post to Instagram with Python without a library?

You do not need an Instagram-specific library. Use an HTTP client such as requests against Meta's official publishing API, with an eligible account, permissioned token, and media.

Can the Instagram API publish a text-only post?

Not through the image flow shown here. The caption belongs to a media container. Include an image or implement the appropriate video publishing flow.

Is a LinkedIn API Python SDK required?

No. Python requests can call the Posts API directly. Authorization, the author URN, the version header, and the request schema still need to be correct.

Does Outstand include X developer credentials?

No. X requires BYOK in Outstand. Supply your own X app credentials and fund the platform access your publishing and analytics operations require.

Does scheduling mean the post has published?

No. Creation confirms the queued job. Read each account's status after its scheduled time, and fetch analytics only after publication.