Gen-AI Developer Classroom notes 22/Jul/2025

MCP Server contd

Using linked in api

"""This module will have necessary functions to post to your linked in
"""
import os
from functools import lru_cache
from dotenv import load_dotenv

from linkedin_api.clients.restli.client import RestliClient

PROFILE_RESOURCE = "/userinfo"
UGC_POSTS_RESOURCE = "/ugcPosts"
POSTS_RESOURCE = "/posts"


@lru_cache(maxsize=128)
def get_user_urn(token: str) -> str:
    """This method gets the user urn

    Args:
        token (str): access token
    """
    linkedin_client = RestliClient()
    profile_response = linkedin_client.get(
        resource_path=PROFILE_RESOURCE,
        access_token=token
    )
    return f"urn:li:person:{profile_response.entity['sub']}"

def create_text_post(token, text = "Sample text post created with /ugcPosts API"):
    """_summary_

    Args:
        token (_type_): _description_
        text (str, optional): _description_. Defaults to "Sample text post created with /ugcPosts API".
    """
    restli_client = RestliClient()
    ugc_posts_create_response = restli_client.create(
        resource_path=UGC_POSTS_RESOURCE,
        entity={
            "author": get_user_urn(token),
            "lifecycleState": "PUBLISHED",
            "specificContent": {
                "com.linkedin.ugc.ShareContent": {
                    "shareCommentary": {
                        "text": text
                    },
                    "shareMediaCategory": "NONE",
                }
            },
            "visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
        },
        access_token=token,
    )
    print(
        f"Successfully created post using /ugcPosts: {ugc_posts_create_response.entity_id}"
    )


if __name__ == "__main__":
    load_dotenv()
    access_token = os.getenv('LINKEDIN_ACCESS_TOKEN')
    urn = get_user_urn(access_token)
    #urn = get_user_urn(access_token)
    create_text_post(access_token,"testing again")
    print(urn)

By continuous learner

enthusiastic technology learner

Leave a Reply

Discover more from Direct AI Powered By Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading