tempest_fastapi_sdk.integrations.social.linkedin¶
LinkedIn: OAuth 2.0 com escopos separados e cliente assíncrono da Posts API e Images API.
LINKEDIN_BASE_URL
module-attribute
¶
Base URL of LinkedIn's REST API host, without trailing slash.
LINKEDIN_API_VERSION
module-attribute
¶
Default LinkedIn-Version header value (YYYYMM) pinned by the SDK.
Override per client via :func:linkedin_http_client or per deployment via
LINKEDIN_API_VERSION on
:class:~tempest_fastapi_sdk.settings.LinkedInSettings.
LINKEDIN_RESTLI_PROTOCOL_VERSION
module-attribute
¶
Rest.li protocol version sent in X-Restli-Protocol-Version.
LINKEDIN_VERSION_HEADER
module-attribute
¶
Header carrying the YYYYMM LinkedIn API version.
LINKEDIN_RESTLI_PROTOCOL_HEADER
module-attribute
¶
Header declaring Rest.li 2.0 protocol semantics.
LINKEDIN_RESTLI_ID_HEADER
module-attribute
¶
Response header carrying the created post URN on 201 from /rest/posts.
LINKEDIN_AUTH_URL
module-attribute
¶
LinkedIn OAuth 2.0 authorization endpoint.
LINKEDIN_TOKEN_URL
module-attribute
¶
LinkedIn OAuth 2.0 token exchange endpoint.
LINKEDIN_USERINFO_PATH
module-attribute
¶
OpenID Connect userinfo endpoint returning sub for urn:li:person:<sub>.
LINKEDIN_PERSONAL_SCOPES
module-attribute
¶
Default OAuth scopes for personal profile publishing.
Intentionally excludes organization scopes so apps without LinkedIn's Community Management API approval are not rejected during consent.
LINKEDIN_ORGANIZATION_SCOPES
module-attribute
¶
LINKEDIN_ORGANIZATION_SCOPES: tuple[str, ...] = (
"openid",
"profile",
"w_organization_social",
"r_organization_social",
)
OAuth scopes for publishing and reading on behalf of organization pages.
Requires LinkedIn's Community Management API product approval on the app;
pass explicitly to :meth:LinkedInOAuthClient.authorization_url only when
the app has those scopes enabled.
validate_linkedin_api_version
¶
Validate a YYYYMM value for the LinkedIn-Version header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_version
|
str
|
Candidate version string (for example |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Stripped, validated |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
linkedin_http_client
¶
linkedin_http_client(
access_token: str,
*,
api_version: str = LINKEDIN_API_VERSION,
base_url: str = LINKEDIN_BASE_URL,
timeout: float = 30.0,
retry_policy: RetryPolicy | None = None,
transport: AsyncBaseTransport | None = None,
) -> HTTPClient
Build an :class:HTTPClient configured for LinkedIn's versioned REST APIs.
Attaches Authorization: Bearer <access_token>, LinkedIn-Version,
X-Restli-Protocol-Version: 2.0.0, Content-Type: application/json,
and Accept: application/json as default headers on every request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
OAuth 2.0 bearer token for the member or organization administrator. |
required |
api_version
|
str
|
|
LINKEDIN_API_VERSION
|
base_url
|
str
|
API host without trailing slash. Override only for a proxy or local fixture server. |
LINKEDIN_BASE_URL
|
timeout
|
float
|
Per-request timeout in seconds. Must be positive
and finite. Defaults to |
30.0
|
retry_policy
|
RetryPolicy | None
|
Optional retry policy; |
None
|
transport
|
AsyncBaseTransport | None
|
Optional transport
override (pass |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
HTTPClient |
HTTPClient
|
Ready-to-use HTTP client for :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
LinkedInOAuthClient
¶
LinkedInOAuthClient(
*,
client_id: str,
client_secret: str,
auth_url: str = LINKEDIN_AUTH_URL,
token_url: str = LINKEDIN_TOKEN_URL,
api_base_url: str = LINKEDIN_BASE_URL,
timeout: float = 30.0,
retry_policy: RetryPolicy | None = None,
transport: AsyncBaseTransport | None = None,
enabled: bool = True,
)
OAuth 2.0 client for LinkedIn authorization, token exchange and userinfo.
Handles the three calls a service needs before constructing a per-user
:class:LinkedInClient:
- :meth:
authorization_urlbuilds the LinkedIn consent URL without mixing organization scopes into personal defaults. - :meth:
exchange_codeswaps the callbackcodefor an access token viaPOST /oauth/v2/accessToken. - :meth:
get_userinforeadsGET /v2/userinfoso the service can obtainuserinfo.person_urn(urn:li:person:<sub>).
Example
oauth = LinkedInOAuthClient( ... client_id="app-id", ... client_secret="app-secret", ... ) url = oauth.authorization_url( ... redirect_uri="https://app.example.com/linkedin/callback", ... state="csrf-token", ... )
Initialize the LinkedIn OAuth client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client_id
|
str
|
LinkedIn OAuth application client id. |
required |
client_secret
|
str
|
LinkedIn OAuth application client secret. |
required |
auth_url
|
str
|
Authorization endpoint URL. Defaults to
:data: |
LINKEDIN_AUTH_URL
|
token_url
|
str
|
Token exchange endpoint URL. Defaults to
:data: |
LINKEDIN_TOKEN_URL
|
api_base_url
|
str
|
LinkedIn API host used for |
LINKEDIN_BASE_URL
|
timeout
|
float
|
Per-request timeout in seconds. Defaults to
|
30.0
|
retry_policy
|
RetryPolicy | None
|
Optional retry policy for outbound HTTP calls. |
None
|
transport
|
AsyncBaseTransport | None
|
Optional transport
override (pass |
None
|
enabled
|
bool
|
Kill-switch mirror of |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
authorization_url
¶
authorization_url(
*, redirect_uri: str, state: str, scopes: Sequence[str] = LINKEDIN_PERSONAL_SCOPES
) -> str
Build the LinkedIn OAuth 2.0 consent URL.
Defaults strictly to :data:LINKEDIN_PERSONAL_SCOPES so personal
member flows never request organization scopes. Pass
:data:LINKEDIN_ORGANIZATION_SCOPES explicitly when the LinkedIn app
is approved for organization publishing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redirect_uri
|
str
|
Exact callback URL registered in the LinkedIn Developer Portal. |
required |
state
|
str
|
Opaque CSRF token generated per login attempt. |
required |
scopes
|
Sequence[str]
|
OAuth scopes to request. Defaults to
:data: |
LINKEDIN_PERSONAL_SCOPES
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Fully encoded authorization URL to redirect the browser to. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
ValueError
|
When |
exchange_code
async
¶
exchange_code(code: str, *, redirect_uri: str) -> LinkedInTokenSchema
Exchange an authorization code for an OAuth access token.
Sends an application/x-www-form-urlencoded POST to
/oauth/v2/accessToken.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Authorization code received on the OAuth callback. |
required |
redirect_uri
|
str
|
Exact callback URL used in
:meth: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
LinkedInTokenSchema |
LinkedInTokenSchema
|
Parsed token payload including |
LinkedInTokenSchema
|
|
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
ValueError
|
When |
LinkedInApiException
|
When LinkedIn rejects the code or cannot be reached. |
get_userinfo
async
¶
get_userinfo(access_token: str) -> LinkedInUserInfoSchema
Fetch the authenticated member's OpenID Connect profile.
Calls GET /v2/userinfo with Authorization: Bearer. Read
userinfo.person_urn on the returned schema to obtain the author
URN (urn:li:person:<sub>) for personal posts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
OAuth 2.0 bearer token granted with
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
LinkedInUserInfoSchema |
LinkedInUserInfoSchema
|
Member profile with |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
ValueError
|
When |
LinkedInApiException
|
When LinkedIn rejects the token ( |
LinkedInClient
¶
LinkedInClient(http: HTTPClient, *, enabled: bool = True)
Async client for publishing posts and images to LinkedIn.
Wrap an :class:~tempest_fastapi_sdk.utils.HTTPClient created by
:func:~tempest_fastapi_sdk.integrations.social.linkedin.linkedin_http_client
so every request carries Authorization: Bearer, LinkedIn-Version
and X-Restli-Protocol-Version: 2.0.0.
Example
http = linkedin_http_client("access-token") async with LinkedInClient(http) as client: ... result = await client.publish_post( ... "urn
person:abc123", ... "Shipping LinkedIn publishing support.", ... ) ... result.post_urn
Initialize the LinkedIn Posts client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
http
|
HTTPClient
|
Pre-configured client from
:func: |
required |
enabled
|
bool
|
Kill-switch mirror of |
True
|
publish_post
async
¶
publish_post(
author_urn: str,
commentary: str,
*,
visibility: LinkedInVisibilityEnum = PUBLIC,
distribution: LinkedInFeedDistributionEnum = MAIN_FEED,
lifecycle_state: LinkedInLifecycleStateEnum = PUBLISHED,
article: LinkedInArticleContentSchema | None = None,
media_urn: str | None = None,
alt_text: str | None = None,
) -> LinkedInPostResultSchema
Create a post on LinkedIn via POST /rest/posts.
Supports text-only posts, external article cards (article), and
single-image posts (media_urn returned by :meth:upload_image).
article and media_urn are mutually exclusive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
author_urn
|
str
|
Author URN ( |
required |
commentary
|
str
|
Post text body. |
required |
visibility
|
LinkedInVisibilityEnum
|
Audience visibility.
Defaults to :attr: |
PUBLIC
|
distribution
|
LinkedInFeedDistributionEnum
|
Feed distribution
mode. Defaults to :attr: |
MAIN_FEED
|
lifecycle_state
|
LinkedInLifecycleStateEnum
|
Initial lifecycle
state. Defaults to :attr: |
PUBLISHED
|
article
|
LinkedInArticleContentSchema | None
|
Optional external
article card. Cannot be combined with |
None
|
media_urn
|
str | None
|
Optional |
None
|
alt_text
|
str | None
|
Optional alt text for |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LinkedInPostResultSchema |
LinkedInPostResultSchema
|
Created post metadata carrying the |
LinkedInPostResultSchema
|
|
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
ValueError
|
When |
LinkedInUnauthorizedException
|
When LinkedIn answers |
LinkedInForbiddenException
|
When LinkedIn answers |
LinkedInRateLimitException
|
When LinkedIn answers |
LinkedInApiException
|
On any other non-2xx response, missing
|
upload_image
async
¶
Upload an image using LinkedIn's two-step Images API flow.
Step 1 initializes the upload via
POST /rest/images?action=initializeUpload with owner_urn.
Step 2 sends the raw image bytes via PUT to the returned
uploadUrl with Content-Type: <content_type>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner_urn
|
str
|
Asset owner URN ( |
required |
data
|
bytes
|
Raw binary image bytes. |
required |
content_type
|
str
|
MIME type sent on the binary |
'image/jpeg'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Uploaded |
str
|
|
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
ValueError
|
When |
LinkedInUnauthorizedException
|
When LinkedIn answers |
LinkedInForbiddenException
|
When LinkedIn answers |
LinkedInRateLimitException
|
When LinkedIn answers |
LinkedInApiException
|
On any other upstream error, malformed initialization payload, or network failure. |
delete_post
async
¶
Delete a post via DELETE /rest/posts/{encoded_post_urn}.
Percent-encodes post_urn with safe="" so : becomes
%3A as required by Rest.li 2.0 path keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
post_urn
|
str
|
Post URN (for example |
required |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When |
ValueError
|
When |
LinkedInUnauthorizedException
|
When LinkedIn answers |
LinkedInForbiddenException
|
When LinkedIn answers |
LinkedInRateLimitException
|
When LinkedIn answers |
LinkedInApiException
|
On any other non-2xx response or network failure. |
LinkedInVisibilityEnum
¶
Bases: BaseStrEnum
Audience visibility for a LinkedIn post.
Attributes:
| Name | Type | Description |
|---|---|---|
PUBLIC |
str
|
Visible to anyone on or off LinkedIn. |
CONNECTIONS |
str
|
Visible only to the author's connections. |
LinkedInFeedDistributionEnum
¶
Bases: BaseStrEnum
Feed distribution target sent in distribution.feedDistribution.
Attributes:
| Name | Type | Description |
|---|---|---|
MAIN_FEED |
str
|
Distribute the post in the main feed. |
NONE |
str
|
Do not distribute in the feed (for example dark posts). |
LinkedInLifecycleStateEnum
¶
Bases: BaseStrEnum
Lifecycle state sent in lifecycleState on POST /rest/posts.
Attributes:
| Name | Type | Description |
|---|---|---|
PUBLISHED |
str
|
Publish immediately. |
DRAFT |
str
|
Save as a draft without publishing. |
LinkedInArticleContentSchema
¶
Bases: BaseSchema
External link preview card attached to a LinkedIn post.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
str
|
Target article URL. |
title |
str
|
Headline rendered on the preview card. |
description |
str | None
|
Optional summary shown below the title. |
thumbnail |
str | None
|
Optional uploaded image URN
( |
to_linkedin_payload
¶
Serialize into the content.article object LinkedIn expects.
Returns:
| Type | Description |
|---|---|
dict[str, JsonValue]
|
dict[str, JsonValue]: Wire dictionary with omitted |
LinkedInMediaUploadSchema
¶
Bases: BaseSchema
Response payload of POST /rest/images?action=initializeUpload.
Attributes:
| Name | Type | Description |
|---|---|---|
upload_url |
str
|
Pre-signed URL that accepts the binary |
image_urn |
str
|
Asset URN ( |
upload_url_expires_at |
int | None
|
Expiration timestamp in epoch milliseconds, when returned by LinkedIn. |
LinkedInPostCreateSchema
¶
Bases: BaseSchema
Input schema for POST /rest/posts.
Validates that author_urn is a person or organization URN, that
article and media_urn are not supplied together (LinkedIn Posts
API treats content variants as mutually exclusive), and that text-only
posts carry non-empty commentary.
Attributes:
| Name | Type | Description |
|---|---|---|
author_urn |
str
|
Author URN ( |
commentary |
str
|
Post text body. |
visibility |
LinkedInVisibilityEnum
|
Audience visibility. |
distribution |
LinkedInFeedDistributionEnum
|
Feed distribution mode. |
lifecycle_state |
LinkedInLifecycleStateEnum
|
Initial lifecycle state. |
article |
LinkedInArticleContentSchema | None
|
Optional article link
card. Mutually exclusive with |
media_urn |
str | None
|
Optional uploaded image URN
( |
alt_text |
str | None
|
Optional accessibility description for
|
to_linkedin_payload
¶
Serialize into the JSON body expected by POST /rest/posts.
Returns:
| Type | Description |
|---|---|
dict[str, JsonValue]
|
dict[str, JsonValue]: Request body matching LinkedIn's versioned |
dict[str, JsonValue]
|
Posts API schema. |
LinkedInPostResultSchema
¶
Bases: BaseSchema
Result returned after creating a post via POST /rest/posts.
LinkedIn returns 201 Created with an empty body and places the new
post URN in the x-restli-id response header.
Attributes:
| Name | Type | Description |
|---|---|---|
post_urn |
str
|
Created post URN read from |
author_urn |
str
|
Author URN the post was created under. |
visibility |
LinkedInVisibilityEnum
|
Requested visibility. |
lifecycle_state |
LinkedInLifecycleStateEnum
|
Requested lifecycle state. |
LinkedInTokenSchema
¶
Bases: BaseSchema
OAuth 2.0 token response from POST /oauth/v2/accessToken.
Attributes:
| Name | Type | Description |
|---|---|---|
access_token |
str
|
Bearer token for LinkedIn API calls. |
expires_in |
int
|
Token lifetime in seconds. |
token_type |
str
|
Token type, typically |
refresh_token |
str | None
|
Optional refresh token when granted by LinkedIn's partner program. |
refresh_token_expires_in |
int | None
|
Optional refresh token lifetime in seconds. |
scope |
str | None
|
Space-separated scopes actually granted. |
LinkedInUserInfoSchema
¶
Bases: BaseSchema
OpenID Connect profile returned by GET /v2/userinfo.
Attributes:
| Name | Type | Description |
|---|---|---|
sub |
str
|
Stable LinkedIn member identifier. |
name |
str | None
|
Full display name, when granted. |
given_name |
str | None
|
First name, when granted. |
family_name |
str | None
|
Last name, when granted. |
email |
str | None
|
Primary e-mail address (requires |
email_verified |
bool | None
|
Whether LinkedIn verified |
picture |
str | None
|
Profile picture URL, when available. |
locale |
str | dict[str, str] | None
|
Locale string or
|
person_urn
property
¶
Build the urn:li:person:<sub> author URN for personal posts.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Author URN ready for :meth: |