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 inYYYYMMformat with month01–12.- Under
ENV=production,production_violations()rejects emptyLINKEDIN_CLIENT_IDorLINKEDIN_CLIENT_SECRETwhileLINKEDIN_ENABLED=True. - With
LINKEDIN_ENABLED=False, production checks are skipped,disabled_integrations()includes"linkedin", and every client operation raisesIntegrationDisabledException("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.0Content-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_imageperforms LinkedIn's two-step Images API flow: firstPOST /rest/images?action=initializeUploadwithowner_urn, then a binaryPUTto the returneduploadUrl, returning theurn:li:image:...URN ready forpublish_post(..., media_urn=...).articleandmedia_urnare mutually exclusive in the Posts API; supplying both or supplyingalt_textwithoutmedia_urnraisesValueErrorlocally before sending any HTTP request.delete_postpercent-encodes the URN (:becomes%3A), issuingDELETE /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¶
LinkedInSettingsvalidatesLINKEDIN_API_VERSION(YYYYMM), guards production boots and exposeslinkedin_oauth_kwargs()andlinkedin_http_kwargs(token).LinkedInOAuthClientkeepsLINKEDIN_PERSONAL_SCOPESseparate fromLINKEDIN_ORGANIZATION_SCOPESand providesuserinfo.person_urn.LinkedInClientattaches required protocol headers vialinkedin_http_client, readsx-restli-idonpublish_post, handles the two-stepupload_imageflow and percent-encodes URNs indelete_post.401,403,429and other failures raise typed subclasses ofLinkedInApiException, andFakeLinkedInClienttests the full flow offline.- Full API surface in the reference:
tempest_fastapi_sdk.integrations.social.linkedin.