LinkedIn API Python Client

repository·main·Indexed 42 days ago

https://github.com/linkedin-developers/linkedin-api-python-client

Official Python client library (v0.3.0) for interacting with LinkedIn's Rest.li-based APIs. It simplifies the Rest.li protocol by handling request formatting, headers, parameter encoding, and OAuth2 authentication. The library provides the RestliClient for performing CRUD operations, batch requests, finder searches, and custom actions, as well as an AuthClient for managing OAuth 2.0 flows.

Tokens
9.2K
Snippets
33
Records
43
Agent score
54%

What's inside LinkedIn API Python Client

  1. Run LinkedIn API Python Client examples

    main

    To run the provided example scripts, follow these steps:

    1. Activate the virtual environment: Use poetry shell.
    2. Navigate to the examples directory: Change your working directory to /examples.
    3. Configure environment variables: Create a .env file in the /examples directory containing your LinkedIn application credentials. Note that specific scripts may require different subsets of these variables or specific OAuth scopes.
    4. Execute the script: Run the desired script using python3 {script_filename}.

    Required .env variables:

    • ACCESS_TOKEN: Your valid access token.
    • CLIENT_ID: Your LinkedIn app client ID.
    • CLIENT_SECRET: Your LinkedIn app client secret.
    • OAUTH2_REDIRECT_URL: Your app's OAuth2 redirect URL.
    # 1. Activate environment
    poetry shell
    
    # 2. Create .env file
    cat <<EOF > .env
    ACCESS_TOKEN="your_valid_access_token"
    CLIENT_ID="your_app_client_id"
    CLIENT_SECRET="your_app_client_secret"
    OAUTH2_REDIRECT_URL="your_app_oauth2_redirect_url"
    EOF
    
    # 3. Run a specific example
    python3 get_profile.py
  2. Make a simple GET request with RestliClient

    main

    Use the RestliClient.get() method to perform a simple GET request. For example, to fetch the current user's information using a 3-legged access token with openid and profile scopes:

    from linkedin_api.clients.restli.client import RestliClient
    
    restli_client = RestliClient()
    
    response = restli_client.get(
      resource_path="/userinfo",
      access_token=<THREE_LEGGED_ACCESS_TOKEN>
    )
    print(response.entity)
  3. Perform a Finder request with complex query parameters

    main

    The finder() method allows you to execute search queries. The client automatically handles URL-encoding for complex objects passed in query_params. For versioned APIs, provide the version_string in YYYYMM format.

    Example: Finding ad accounts with specific statuses and references (requires r_ads scope):

    from linkedin_api.clients.restli.client import RestliClient
    
    restli_client = RestliClient()
    
    response = restli_client.finder(
      resource_path="/adAccounts",
      finder_name="search",
      query_params={
        "search": {
          "status": {
            "values": ["ACTIVE", "DRAFT"]
          },
          "reference": {
            "values": ["urn:li:organization:123"]
          },
          "test": True
        }
      },
      version_string="202212",
      acccess_token=<THREE_LEGGED_ACCESS_TOKEN>
    )
    ad_accounts = response.elements
  4. Fetch all entities with get_all()

    main

    Use get_all() to perform a Rest.li GET_ALL request to fetch all entities on a resource. It returns a CollectionResponse object.

    Example usage:

    response = restli_client.get_all(
      resource_path="/fieldsOfStudy",
      query_params={
        "start": 0,
        "count": 15
      },
      access_token=MY_ACCESS_TOKEN,
      version_string="202212"
    )
    fields_of_study = response.elements
    total = response.paging.total
  5. Perform a custom action with action()

    main

    Use action() to perform a Rest.li ACTION request. This is a flexible method used when an operation does not fit standard CRUD behaviors. It returns an ActionResponse object.

    Additional Parameters:

    • action_name: str (Required) - The action method name, added to query parameters.
    • action_params: Dict[str,Any] (Optional) - A map of action parameters sent in the request body.
    response = restli_client.action(
      resource_path="/liveAssetActions",
      action_name="register",
      action_params={
        "registerLiveEventRequest": {
          "owner": "urn:li:person:12345",
          "recipes": ["urn:li:digitalmediaRecipe:feedshare-live-video"],
          "region": "WEST_US"
        }
      },
      access_token=MY_ACCESS_TOKEN
    )
    status_code = response.status_code
  6. Perform a partial update with partial_update()

    main

    Use partial_update() to perform a Rest.li PARTIAL_UPDATE request. This allows you to update only specific fields of an entity rather than overwriting the whole thing. It returns an UpdateResponse object.

    Note: While the Rest.li protocol supports granular nested updates, most LinkedIn APIs only support partial updates on top-level fields.

    Additional Parameter:

    • patch_set_object: Dict[str,Any] (Required) - A dictionary containing only the modified fields. This is sent in the request body as patch: { $set: patch_set_object }.
    response = restli_client.partial_update(
      resource_path="/adAccounts/{id}",
      path_keys={ "id": 123 },
      patch_set_object={
        "name": "TestAdAccountModified",
        "reference": "urn:li:organization:456"
      },
      access_token=MY_ACCESS_TOKEN,
      version_string="202212"
    )
    status = response.status_code
  7. Find entities with finder()

    main

    Use finder() to perform a Rest.li FINDER request to search for entities based on specific criteria. It returns a CollectionResponse object.

    Additional Parameter:

    • finder_name: str (Required) - The Rest.li finder name, which is added to the request query parameters.
    response = restli_client.finder(
      resource_path="/adAccounts",
      finder_name="search",
      query_params={
        "search": {
            "status": {
                "values": ["ACTIVE", "DRAFT", "CANCELED"]
            },
            "reference": {
                "values": ["urn:li:organization:123"]
            },
            "test": False
        },
        "start": 0,
        "count": 5
      },
      access_token=MY_ACCESS_TOKEN,
      version_string="202212"
    )
    ad_accounts = response.elements
    total = response.paging.total