Skip to content

LinkedIn (OAuth and Posts API)

Use tempest_fastapi_sdk.integrations.social.linkedin to authenticate members over OAuth 2.0, publish text, article or image posts through LinkedIn's versioned Posts API (/rest/posts and /rest/images), delete posts, and test publishing flows offline with FakeLinkedInClient.

No extra is needed: the integration depends only on httpx, which is already in the SDK's base install.

Verification scope

Endpoint paths, headers (LinkedIn-Version, X-Restli-Protocol-Version: 2.0.0, x-restli-id), OAuth scopes and request/response shapes for /rest/posts, /rest/images?action=initializeUpload, /oauth/v2/accessToken and /v2/userinfo are derived from LinkedIn's official Marketing / Community Management API documentation. All client behaviour in this SDK was verified offline against httpx.MockTransport — no live LinkedIn account was called.

1. Configuration with LinkedInSettings

Use LinkedInSettings to load OAuth credentials from environment variables, pin the LinkedIn-Version (YYYYMM) header and wire the LINKEDIN_ENABLED kill-switch alongside EnvironmentSettings.

from tempest_fastapi_sdk.integrations.social.linkedin import (
    LinkedInClient,
    LinkedInOAuthClient,
    linkedin_http_client,
)
from tempest_fastapi_sdk.settings import (
    BaseAppSettings,
    EnvironmentSettings,
    LinkedInSettings,
)


class AppSettings(EnvironmentSettings, LinkedInSettings, BaseAppSettings):
    """Application settings with production guard for LinkedIn."""


def build_oauth_client(settings: AppSettings) -> LinkedInOAuthClient:
    """Build the OAuth client from environment settings."""
    return LinkedInOAuthClient(**settings.linkedin_oauth_kwargs())


def build_posts_client(
    settings: AppSettings,
    access_token: str,
) -> LinkedInClient:
    """Build a Posts API client for a user's OAuth bearer token."""
    http = linkedin_http_client(**settings.linkedin_http_kwargs(access_token))
    return LinkedInClient(http, enabled=settings.LINKEDIN_ENABLED)

What the mixin enforces:

  • LINKEDIN_API_VERSION (default "202505") is validated at boot in YYYYMM format with month 01–12.
  • Under ENV=production, production_violations() rejects empty LINKEDIN_CLIENT_ID or LINKEDIN_CLIENT_SECRET while LINKEDIN_ENABLED=True.
  • With LINKEDIN_ENABLED=False, production checks are skipped, disabled_integrations() includes "linkedin", and every client operation raises IntegrationDisabledException("linkedin") (503).

2. OAuth 2.0: personal vs. organization scopes

Use LinkedInOAuthClient to build the consent URL, exchange the callback code for an access token and call /v2/userinfo to obtain the member's person_urn (urn:li:person:<sub>).

By default, authorization_url requests only LINKEDIN_PERSONAL_SCOPES (openid, profile, w_member_social) and never mixes organization scopes into personal defaults — preventing consent errors on apps without LinkedIn's Community Management API approval. Pass LINKEDIN_ORGANIZATION_SCOPES explicitly when publishing for company pages.

import asyncio

from tempest_fastapi_sdk.integrations.social.linkedin import (
    LINKEDIN_ORGANIZATION_SCOPES,
    LinkedInOAuthClient,
)


async def run_oauth_flow(code: str) -> str:
    """Build consent URLs, exchange the code and return the member person_urn."""
    redirect_uri: str = "https://app.example.com/auth/linkedin/callback"
    async with LinkedInOAuthClient(
        client_id="app-client-id",
        client_secret="app-client-secret",
    ) as oauth:
        personal_url: str = oauth.authorization_url(
            redirect_uri=redirect_uri,
            state="csrf-state-1",
        )
        org_url: str = oauth.authorization_url(
            redirect_uri=redirect_uri,
            state="csrf-state-2",
            scopes=LINKEDIN_ORGANIZATION_SCOPES,
        )
        _ = (personal_url, org_url)

        token = await oauth.exchange_code(code, redirect_uri=redirect_uri)
        userinfo = await oauth.get_userinfo(token.access_token)
        return userinfo.person_urn


if __name__ == "__main__":
    print(asyncio.run(run_oauth_flow("demo-code")))

3. Publish text, articles and images via Posts API

Use linkedin_http_client + LinkedInClient to publish on personal profiles (urn:li:person:...) or organization pages (urn:li:organization:...).

Every request built by linkedin_http_client attaches:

  • Authorization: Bearer <access_token>
  • LinkedIn-Version: <YYYYMM>
  • X-Restli-Protocol-Version: 2.0.0
  • Content-Type: application/json

LinkedIn answers 201 Created with an empty body and places the created post URN in the x-restli-id header, which publish_post reads into LinkedInPostResultSchema.post_urn.

import asyncio

from tempest_fastapi_sdk.integrations.social.linkedin import (
    LinkedInArticleContentSchema,
    LinkedInClient,
    LinkedInLifecycleStateEnum,
    LinkedInVisibilityEnum,
    linkedin_http_client,
)


async def publish_examples(access_token: str, author_urn: str) -> None:
    """Publish an article post and an image post, then delete the media post."""
    http = linkedin_http_client(access_token, api_version="202505")
    async with LinkedInClient(http) as client:
        article_post = await client.publish_post(
            author_urn,
            "Release notes for our new version.",
            visibility=LinkedInVisibilityEnum.PUBLIC,
            lifecycle_state=LinkedInLifecycleStateEnum.PUBLISHED,
            article=LinkedInArticleContentSchema(
                source="https://example.com/blog/release",
                title="Release notes",
                description="Technical summary of the changes.",
            ),
        )
        print(article_post.post_urn)

        image_urn: str = await client.upload_image(
            author_urn,
            b"\x89PNG\r\n\x1a\nexample-bytes",
            content_type="image/png",
        )
        media_post = await client.publish_post(
            author_urn,
            "Updated architecture diagram.",
            media_urn=image_urn,
            alt_text="Architecture diagram",
        )
        print(media_post.post_urn)

        await client.delete_post(media_post.post_urn)


if __name__ == "__main__":
    asyncio.run(publish_examples("access-token", "urn:li:person:abc123"))

Key details:

  • upload_image performs LinkedIn's two-step Images API flow: first POST /rest/images?action=initializeUpload with owner_urn, then a binary PUT to the returned uploadUrl, returning the urn:li:image:... URN ready for publish_post(..., media_urn=...).
  • article and media_urn are mutually exclusive in the Posts API; supplying both or supplying alt_text without media_urn raises ValueError locally before sending any HTTP request.
  • delete_post percent-encodes the URN (: becomes %3A), issuing DELETE /rest/posts/urn%3Ali%3Ashare%3A... as required by Rest.li 2.0.

4. Typed error handling

Use the LinkedInApiException hierarchy to branch on expired tokens, missing scopes and rate limits without parsing raw httpx errors.

LinkedIn HTTP status Exception code Your API status_code
401 LinkedInUnauthorizedException LINKEDIN_UNAUTHORIZED 502
403 LinkedInForbiddenException LINKEDIN_FORBIDDEN 502
429 LinkedInRateLimitException LINKEDIN_RATE_LIMITED 503
Other / network error LinkedInApiException LINKEDIN_API_ERROR 502

Every subclass inherits from LinkedInApiException and ships both pt-BR and en-US translations in the default exception catalog. On 429 responses with a numeric Retry-After header, the delay is exposed as exc.retry_after.

from tempest_fastapi_sdk.exceptions import (
    LinkedInApiException,
    LinkedInForbiddenException,
    LinkedInRateLimitException,
    LinkedInUnauthorizedException,
)
from tempest_fastapi_sdk.integrations.social.linkedin import LinkedInClient


async def publish_safely(
    client: LinkedInClient,
    author_urn: str,
    text: str,
) -> str | None:
    """Publish a post and classify common LinkedIn API failures."""
    try:
        result = await client.publish_post(author_urn, text)
        return result.post_urn
    except LinkedInUnauthorizedException:
        return None
    except LinkedInForbiddenException:
        raise
    except LinkedInRateLimitException as exc:
        _ = exc.retry_after
        return None
    except LinkedInApiException:
        raise

5. Offline testing with FakeLinkedInClient

Use FakeLinkedInClient in service tests to record published posts, uploaded images and deleted post URNs in memory while enforcing the same URN validation and steering failures via fail_next.

import asyncio

from tempest_fastapi_sdk.exceptions import LinkedInRateLimitException
from tempest_fastapi_sdk.testing.fakes import FakeLinkedInClient


async def test_publishing_service() -> None:
    """Exercise image upload, publish, delete and rate-limit failure in memory."""
    async with FakeLinkedInClient() as fake:
        image_urn: str = await fake.upload_image(
            "urn:li:organization:42",
            b"jpeg-bytes",
            content_type="image/jpeg",
        )
        result = await fake.publish_post(
            "urn:li:organization:42",
            "New feature shipped.",
            media_urn=image_urn,
            alt_text="Launch banner",
        )
        await fake.delete_post(result.post_urn)

        assert len(fake.uploaded_images) == 1
        assert len(fake.published_posts) == 1
        assert fake.deleted_posts == [result.post_urn]

        fake.fail_next(LinkedInRateLimitException(retry_after=60.0))
        try:
            await fake.publish_post("urn:li:organization:42", "Second post")
        except LinkedInRateLimitException as exc:
            assert exc.retry_after == 60.0


if __name__ == "__main__":
    asyncio.run(test_publishing_service())

Recap

  • LinkedInSettings validates LINKEDIN_API_VERSION (YYYYMM), guards production boots and exposes linkedin_oauth_kwargs() and linkedin_http_kwargs(token).
  • LinkedInOAuthClient keeps LINKEDIN_PERSONAL_SCOPES separate from LINKEDIN_ORGANIZATION_SCOPES and provides userinfo.person_urn.
  • LinkedInClient attaches required protocol headers via linkedin_http_client, reads x-restli-id on publish_post, handles the two-step upload_image flow and percent-encodes URNs in delete_post.
  • 401, 403, 429 and other failures raise typed subclasses of LinkedInApiException, and FakeLinkedInClient tests the full flow offline.
  • Full API surface in the reference: tempest_fastapi_sdk.integrations.social.linkedin.