Ir para o conteúdo

tempest_fastapi_sdk.integrations.social.linkedin

LinkedIn: OAuth 2.0 com escopos separados e cliente assíncrono da Posts API e Images API.

« Integrações e pagamentos


LINKEDIN_BASE_URL module-attribute

LINKEDIN_BASE_URL: str = 'https://api.linkedin.com'

Base URL of LinkedIn's REST API host, without trailing slash.

LINKEDIN_API_VERSION module-attribute

LINKEDIN_API_VERSION: str = '202505'

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

LINKEDIN_RESTLI_PROTOCOL_VERSION: str = '2.0.0'

Rest.li protocol version sent in X-Restli-Protocol-Version.

LINKEDIN_VERSION_HEADER module-attribute

LINKEDIN_VERSION_HEADER: str = 'LinkedIn-Version'

Header carrying the YYYYMM LinkedIn API version.

LINKEDIN_RESTLI_PROTOCOL_HEADER module-attribute

LINKEDIN_RESTLI_PROTOCOL_HEADER: str = 'X-Restli-Protocol-Version'

Header declaring Rest.li 2.0 protocol semantics.

LINKEDIN_RESTLI_ID_HEADER module-attribute

LINKEDIN_RESTLI_ID_HEADER: str = 'x-restli-id'

Response header carrying the created post URN on 201 from /rest/posts.

LINKEDIN_AUTH_URL module-attribute

LINKEDIN_AUTH_URL: str = 'https://www.linkedin.com/oauth/v2/authorization'

LinkedIn OAuth 2.0 authorization endpoint.

LINKEDIN_TOKEN_URL module-attribute

LINKEDIN_TOKEN_URL: str = 'https://www.linkedin.com/oauth/v2/accessToken'

LinkedIn OAuth 2.0 token exchange endpoint.

LINKEDIN_USERINFO_PATH module-attribute

LINKEDIN_USERINFO_PATH: str = '/v2/userinfo'

OpenID Connect userinfo endpoint returning sub for urn:li:person:<sub>.

LINKEDIN_PERSONAL_SCOPES module-attribute

LINKEDIN_PERSONAL_SCOPES: tuple[str, ...] = ('openid', 'profile', 'w_member_social')

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_linkedin_api_version(api_version: str) -> str

Validate a YYYYMM value for the LinkedIn-Version header.

Parameters:

Name Type Description Default
api_version str

Candidate version string (for example "202505").

required

Returns:

Name Type Description
str str

Stripped, validated YYYYMM version string.

Raises:

Type Description
ValueError

When api_version does not match YYYYMM or its month component is outside 01-12.

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

YYYYMM string sent in LinkedIn-Version. Defaults to :data:LINKEDIN_API_VERSION.

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.

30.0
retry_policy RetryPolicy | None

Optional retry policy; None keeps the SDK default.

None
transport AsyncBaseTransport | None

Optional transport override (pass httpx.MockTransport in offline tests).

None

Returns:

Name Type Description
HTTPClient HTTPClient

Ready-to-use HTTP client for :class:LinkedInClient.

Raises:

Type Description
ValueError

When access_token is empty, api_version is not a valid YYYYMM string, base_url is empty, or timeout is not a finite positive number.

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:

  1. :meth:authorization_url builds the LinkedIn consent URL without mixing organization scopes into personal defaults.
  2. :meth:exchange_code swaps the callback code for an access token via POST /oauth/v2/accessToken.
  3. :meth:get_userinfo reads GET /v2/userinfo so the service can obtain userinfo.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.

LINKEDIN_AUTH_URL
token_url str

Token exchange endpoint URL. Defaults to :data:LINKEDIN_TOKEN_URL.

LINKEDIN_TOKEN_URL
api_base_url str

LinkedIn API host used for /v2/userinfo. Defaults to :data:LINKEDIN_BASE_URL.

LINKEDIN_BASE_URL
timeout float

Per-request timeout in seconds. Defaults to 30.0.

30.0
retry_policy RetryPolicy | None

Optional retry policy for outbound HTTP calls.

None
transport AsyncBaseTransport | None

Optional transport override (pass httpx.MockTransport in tests).

None
enabled bool

Kill-switch mirror of LINKEDIN_ENABLED. When False, every method raises :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException.

True

Raises:

Type Description
ValueError

When auth_url, token_url or api_base_url is empty, or timeout is not a finite positive number.

aclose async

aclose() -> None

Close the underlying HTTP connection pool. Safe to call twice.

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.

LINKEDIN_PERSONAL_SCOPES

Returns:

Name Type Description
str str

Fully encoded authorization URL to redirect the browser to.

Raises:

Type Description
IntegrationDisabledException

When enabled is False.

ValueError

When client_id, redirect_uri, state or scopes is empty or contains blank entries.

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:authorization_url.

required

Returns:

Name Type Description
LinkedInTokenSchema LinkedInTokenSchema

Parsed token payload including

LinkedInTokenSchema

access_token and expires_in.

Raises:

Type Description
IntegrationDisabledException

When enabled is False.

ValueError

When client_id, client_secret, code or redirect_uri is empty.

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 openid and profile scopes.

required

Returns:

Name Type Description
LinkedInUserInfoSchema LinkedInUserInfoSchema

Member profile with person_urn.

Raises:

Type Description
IntegrationDisabledException

When enabled is False.

ValueError

When access_token is empty.

LinkedInApiException

When LinkedIn rejects the token (401/ 403/429) or cannot be reached.

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:linkedin_http_client.

required
enabled bool

Kill-switch mirror of LINKEDIN_ENABLED. When False, every operation raises :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException.

True

aclose async

aclose() -> None

Close the wrapped :class:HTTPClient. Safe to call twice.

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 (urn:li:person:<id> for personal posts or urn:li:organization:<id> for company pages).

required
commentary str

Post text body.

required
visibility LinkedInVisibilityEnum

Audience visibility. Defaults to :attr:LinkedInVisibilityEnum.PUBLIC.

PUBLIC
distribution LinkedInFeedDistributionEnum

Feed distribution mode. Defaults to :attr:LinkedInFeedDistributionEnum.MAIN_FEED.

MAIN_FEED
lifecycle_state LinkedInLifecycleStateEnum

Initial lifecycle state. Defaults to :attr:LinkedInLifecycleStateEnum.PUBLISHED.

PUBLISHED
article LinkedInArticleContentSchema | None

Optional external article card. Cannot be combined with media_urn.

None
media_urn str | None

Optional urn:li:image:... from :meth:upload_image. Cannot be combined with article.

None
alt_text str | None

Optional alt text for media_urn.

None

Returns:

Name Type Description
LinkedInPostResultSchema LinkedInPostResultSchema

Created post metadata carrying the

LinkedInPostResultSchema

post_urn read from the x-restli-id response header.

Raises:

Type Description
IntegrationDisabledException

When enabled is False.

ValueError

When author_urn or media_urn is malformed, both article and media_urn are given, alt_text is given without media_urn, or a text-only post has empty commentary.

LinkedInUnauthorizedException

When LinkedIn answers 401.

LinkedInForbiddenException

When LinkedIn answers 403.

LinkedInRateLimitException

When LinkedIn answers 429.

LinkedInApiException

On any other non-2xx response, missing x-restli-id header, or network failure.

upload_image async

upload_image(owner_urn: str, data: bytes, *, content_type: str = 'image/jpeg') -> str

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 (urn:li:person:<id> or urn:li:organization:<id>). Must match the author_urn used in :meth:publish_post.

required
data bytes

Raw binary image bytes.

required
content_type str

MIME type sent on the binary PUT step. Defaults to "image/jpeg".

'image/jpeg'

Returns:

Name Type Description
str str

Uploaded urn:li:image:... URN ready for

str

publish_post(..., media_urn=...).

Raises:

Type Description
IntegrationDisabledException

When enabled is False.

ValueError

When owner_urn is malformed, data is empty, or content_type is blank.

LinkedInUnauthorizedException

When LinkedIn answers 401.

LinkedInForbiddenException

When LinkedIn answers 403.

LinkedInRateLimitException

When LinkedIn answers 429.

LinkedInApiException

On any other upstream error, malformed initialization payload, or network failure.

delete_post async

delete_post(post_urn: str) -> None

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 urn:li:share:... or urn:li:ugcPost:...).

required

Raises:

Type Description
IntegrationDisabledException

When enabled is False.

ValueError

When post_urn is malformed or contains path traversal segments.

LinkedInUnauthorizedException

When LinkedIn answers 401.

LinkedInForbiddenException

When LinkedIn answers 403.

LinkedInRateLimitException

When LinkedIn answers 429.

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 (urn:li:image:...) used as the card thumbnail.

to_linkedin_payload

to_linkedin_payload() -> dict[str, JsonValue]

Serialize into the content.article object LinkedIn expects.

Returns:

Type Description
dict[str, JsonValue]

dict[str, JsonValue]: Wire dictionary with omitted None keys.

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 PUT.

image_urn str

Asset URN (urn:li:image:...) referenced in publish_post(..., media_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 (urn:li:person:... or urn:li:organization:...).

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.

media_urn str | None

Optional uploaded image URN (urn:li:image:...). Mutually exclusive with article.

alt_text str | None

Optional accessibility description for media_urn.

to_linkedin_payload

to_linkedin_payload() -> dict[str, JsonValue]

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 x-restli-id.

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 "Bearer".

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 scope).

email_verified bool | None

Whether LinkedIn verified email.

picture str | None

Profile picture URL, when available.

locale str | dict[str, str] | None

Locale string or {"country": ..., "language": ...} object returned by LinkedIn.

person_urn property

person_urn: str

Build the urn:li:person:<sub> author URN for personal posts.

Returns:

Name Type Description
str str

Author URN ready for :meth:LinkedInClient.publish_post.