Package: linkedin-api-client
LinkedIn API Python ClientOverviewThis library provides a thin Python client for making requests to LinkedIn APIs, utilizing the PythonrequestsHTTP client library. LinkedIn's APIs are built on theRest.liframework with additional LinkedIn-specific constraints, which results in a robust yet complex protocol that can be challenging to implement correctly.This library helps reduce this complexity by formatting requests correctly, providing proper request headers, and providing interfaces to develop against for responses. The library also provides an auth client for inspecting, generating, and refreshing access tokens, along with other helpful utilities.:warning: This API client library is currently in beta and is subject to change. It may contain bugs, errors, or other issues that we are working to resolve. Use of this library is at your own risk. Please use caution when using it in production environments and be prepared for the possibility of unexpected behavior. We welcome any feedback or reports of issues that you may encounter while using this library.FeaturesGeneric support for all Rest.li methods used in LinkedIn APIsSupports Rest.li protocol version 2.0.0Provide interfaces for request options/response payloadsBuilt-in parameter encodingUtilities (e.g. URN handling, encoding)Supports versioned APIsAutomatic query tunneling of requests2-legged and 3-legged OAuth2 supportTable of ContentsRequirementsInstallationGetting StartedPre-requisitesSimple API Request ExampleFinder Request ExampleMore ExamplesAPI ReferenceRestliClientConstructorPropertiesMethodsget()batch_get()get_all()finder()batch_finder()create()batch_create()update()batch_update()partial_update()batch_partial_update()delete()batch_delete()action()AuthClientConstructorPropertiesMethodsgenerate_member_auth_url()exchange_auth_code_for_access_token()exchange_refresh_token_for_access_token()get_two_legged_access_token()introspect_access_token()List of dependenciesRequirementsPython >= 3.7Installationpipinstalllinkedin-api-clientGetting StartedPre-requisitesCreate or use an existing developer application from theLinkedIn Developer PortalRequest access to the Sign In With LinkedIn API product. This is a self-serve product that will be provisioned immediately to your application.Generate a 3-legged access token using the Developer Portaltoken generator tool, selecting the r_liteprofile scope.Simple API Request ExampleHere is an example of using the client to make a simple GET request tofetch the current user's profile. This requires a 3-legged access token with the "r_liteprofile" scope, which is included with the Sign In With LinkedIn API product.fromlinkedin_api.clients.restli.clientimportRestliClientrestli_client=RestliClient()response=restli_client.get(resource_path="/me",access_token=<THREE_LEGGED_ACCESS_TOKEN>)print(response.entity)Finder Request ExampleHere is a more non-trivial example tofind ad accountsby some search criteria. This requires a 3-legged access token with the "r_ads" scope, which is included with the Advertising APIs product.The "search" query parameter in this case is not a primitive, but a complex object, which we represent as a dictionary. The client will handle the correct URL-encoding. This is a versioned API call, so we also need to provide the version string in the "YYYYMM" format.fromlinkedin_api.clients.restli.clientimportRestliClientrestli_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.elementsMore ExamplesThere are more examples of using the client in/examplesdirectory.API Referenceclass RestliClientThe Rest.li API client defines instance methods for all the Rest.li methods which are used by LinkedIn APIs. All calls are blocking.Rest.li defines a standard set of methods that can operate on a resource, each of which maps to an HTTP method. Depending on the resource, some Rest.li methods are not applicable or not implemented. Read the API docs to determine what Rest.li method is applicable and the relevant request parameters.ConstructorAn instance of the API client must be created before using. This creates a session object that will be used for making all subsequent requests.fromlinkedin_api.clients.restli.clientimportRestliClientrestli_client=RestliClient()The Requests librarysessionobject is accessible to configure any additional global settings (e.g. configuring event hooks).restli_client.session.hooks={'response':[do_something_fn,do_something_2_fn]}PropertiesPropertyDescriptionsessionThe session object used for making http requests. This is exposed to allow for additional configuration (e.g. adding custom request/response event hooks).MethodsBase Request ParametersAll Rest.li request methods of the API client support the following request parameters:ParameterTypeRequired?Descriptionresource_pathstrYesThe resource path after the base URL, beginning with a forward slash. If the path contains keys, add curly-brace placeholders for the keys and specify the path key-value map in thepath_keysargument.Examples:resource_path="/me"resource_path="/adAccounts/{id}"resource_path="/socialActions/{actionUrn}/comments/{commentId}"resource_path="/campaignConversions/{key}access_tokenstrYesThe access token that should provide the application access to the specified APIpath_keysDict[str,Any]NoIf there are path keys that are part of theresource_pathargument, the key placeholders must be specified in the providedpath_keysmap. The path key values can be strings, numbers, or objects (dictionaries), and these will be properly encoded.Examples:path_keys={"id": 123"}path_keys={"actionUrn":"urn:li:share:123","commentId":987}path_keys={"key": {"campaign": "urn:li:sponsoredCampaign:123", "conversion": "urn:lla:llaPartnerConversion:456"}}query_paramsDict[str,Any]NoA map of query parameters. The query parameter values (strings, lists, objects) will be correctly encoded by this method, so these should not be encoded.version_stringstrNoAn optional version string of the format "YYYYMM" or "YYYYMM.RR". If specified, the version header will be passed and the request will use the versioned APIs base URLget (resource_path, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li GET request to fetch the specified entity on a resource. This method will perform query tunneling if necessary.Parameters:This method only uses thebase request parametersdefined above.Return value:ReturnsGetResponseobjectExample:response=restli_client.get(resource_path="/adAccounts/{id}"path_keys={"id":123},query_params={"fields":"id,name"}access_token=MY_ACCESS_TOKEN,version_string="202212")ad_account=response.entitybatch_get (resource_path, ids, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li BATCH_GET request to fetch multiple entities on a resource. This method will perform query tunneling if necessary.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionidsList[Union[str,int,Dict[str,Any]]]YesThe list of entity ids to fetch on the resource. These will be encoded and added to the query parameters.Return value:Returns aBatchGetResponseobject.Example:response=restli_client.batch_get(resource_path="/adCampaignGroups",ids=[123,456,789],access_token=MY_ACCESS_TOKEN,version_string="202212")campaign_groups=response.results.items()get_all (resource_path, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li GET_ALL request to fetch all entities on a resource.Parameters:This method only uses thebase request parametersdefined above.Return value:ReturnsCollectionResponseobjectExample: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.elementstotal=response.paging.totalfinder (resource_path, finder_name, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li FINDER request to find entities by some specified criteria.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?Descriptionfinder_namestrYesThe Rest.li finder name. This will be added to the request query parameters.Return value:Returns aCollectionResponseobject.Example: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.elementstotal=response.paging.totalbatch_finder (resource_path, finder_name, finder_criteria, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li BATCH_FINDER request to find entities by multiple sets of criteria.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?Descriptionfinder_namestrYesThe Rest.li batch finder name (the value of the "bq" query parameter). This will be added to the request query parameters.finder_criteriaTuple[str, List[Dict[str,Any]]]YesThe required batch finder criteria information. This is a tuple with the first value being the batch finder criteria parameter name. The second value is the list of finder param objects. The batch finder results are correspondingly ordered according to this list. The batch finder criteria will be encoded and added to the request query parameters.Return value:Returns aBatchFinderResponseobject.Example:response=restli_client.batch_finder(resource_path="/organizationAuthorizations",finder_name="authorizationActionsAndImpersonator",finder_criteria=("authorizationActions",[{"OrganizationRoleAuthorizationAction":{actionType:"ADMINISTRATOR_READ"}},{"OrganizationContentAuthorizationAction":{actionType:"ORGANIC_SHARE_DELETE"}}]),access_token=MY_ACCESS_TOKEN,version_string="202212")admin_read_authorizations=response.results[0].elementsorganic_share_delete_authorizations=response.results[1].elementscreate (resource_path, entity, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li CREATE request to create a new resource entity.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionentityDict[str,Any]YesA dictionary representation of the entity to createReturn value:Returns aCreateResponseobject.Example:response=restli_client.create(resource_path="/adAccountsV2",entity={"name":"Test Ad Account","type":"BUSINESS","test":True},access_token=MY_ACCESS_TOKEN)created_entity_id=response.entity_idbatch_create (resource_path, entities, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li BATCH_CREATE request to create multiple entities in a single call.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionentitiesList[Dict[str,Any]]YesA list of entities to createReturn value:Returns aBatchCreateResponseobject.Example:response=restli_client.batch_create(resource_path="/adCampaignGroups",entities=[{account:'urn:li:sponsoredAccount:111',name:'CampaignGroupTest1',status:'DRAFT'},{account:'urn:li:sponsoredAccount:222',name:'CampaignGroupTest2',status:'DRAFT'}],access_token=MY_ACCESS_TOKEN,version_string="202212")created_elements=response.elementsfirst_created_element_id=response.elements[0].idupdate (resource_path, entity, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li UPDATE request to update an entity (overwriting the entity with the provided value).Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionentityDict[str,Any]YesThe value of the updated entity. This will completely overwrite the entity.Return value:Returns aUpdateResponseobject.Example:response=restli_client.update(resource_path="/adAccountUsers/{id}",path_keys={"id":{"account":"urn:li:sponsoredAccount:123","user":"urn:li:person:foobar"}},entity:{"account":"urn:li:sponsoredAccount:123","user":"urn:li:person:foobar","role":"VIEWER"},access_token=MY_ACCESS_TOKEN,version_string="202212")status=response.status_codebatch_update (resource_path, ids, entities, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li BATCH_UPDATE request to update multiple entities in a single call.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionidsList[Union[str,int,Dict[str,Any]]]YesThe ids of the entities to updateentitiesList[Dict[str,Any]]YesThe values to update the specified entities to. This should be the same order as theidsargument.Return value:Returns aBatchUpdateResponseobject.Example:response=restli_client.batch_update(resource_path="/campaignConversions",ids=[{"campaign":"urn:li:sponsoredCampaign:123","conversion":"urn:lla:llaPartnerConversion:456"},{"campaign":"urn:li:sponsoredCampaign:123","conversion":"urn:lla:llaPartnerConversion:789"}],entities=[{"campaign":"urn:li:sponsoredCampaign:123","conversion":"urn:lla:llaPartnerConversion:456"},{"campaign":"urn:li:sponsoredCampaign:123","conversion":"urn:lla:llaPartnerConversion:789"}],access_token=MY_ACCESS_TOKEN,version_string="202212")batch_results=response.results.items()partial_update (resource_path, patch_set_object, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li PARTIAL_UPDATE request to update part of an entity. Directly specify the patch object to send in the request.Note: While the Rest.li protocol supports very granular patch objects with setting and deletion of nested properties, most LinkedIn APIs only support partial update on the top-level fields of an entity.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?Descriptionpatch_set_objectDict[str,Any]YesThe value of the entity with only the modified fields present. This will be sent directly in the request body aspatch: { $set: patch_set_object }.Return value:Returns aUpdateResponseobject.Example: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_codebatch_partial_update (resource_path, ids, patch_set_objects, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li BATCH_PARTIAL_UPDATE request to update multiple entities at once, by only providing the fields of the entities that require updating.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionidsList[Union[str,int,Dict[str,Any]]]YesThe list of entity ids to update. These will be encoded and added to the query parameters.patch_set_objectsList[Dict[str,Any]]YesThe list of entity values, represented as a dictionary, with only the modified fields present.Return value:Returns aBatchUpdateResponseobject.Example:response=restli_client.batch_partial_update(resource_path="/adCampaignGroups",ids=["123","456"],patch_set_objects:[{"status":"ACTIVE"},{"runSchedule":{"start":1678029270721,"end":1679029270721}}],access_token=MY_ACCESS_TOKEN,version_string="202212")result_status=response.results["123"].statusdelete (resource_path, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li DELETE request to delete an entity.Parameters:This method only uses thebase request parametersdefined above.Return value:ReturnsBaseRestliResponseobjectExample:response=restli_client.delete(resource_path="/adAccounts/{id}",path_keys={"id":123},access_token=MY_ACCESS_TOKEN,version_string="202212")status_code=response.status_codebatch_delete (resource_path, ids, access_token, path_keys=None, query_params=None, version_string=None)Makes a Rest.li BATCH_DELETE request to delete multiple entities at once.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?DescriptionidsList[Union[str,int,Dict[str,Any]]]YesThe list of entity ids to delete. These will be encoded and added to the query parameters.Return value:ReturnsBatchDeleteResponseobjectExample:response=restli_client.batch_delete(resource_path="/adAccounts",ids=["123","456"],access_token=MY_ACCESS_TOKEN,version_string="202212")status_code=response.results["123"].statusaction (resource_path, action_name, access_token, action_params=None, path_keys=None, query_params=None, version_string=None)Makes a Rest.li ACTION request to perform an action on a specified resource. This method is flexible and generally used when the action does not fit within the standard behavior defined by the other Rest.li methods.Parameters:The additional parameters besides thebase request parametersare:ParameterTypeRequired?Descriptionaction_namestrYesThe action method name. This will be added to the query parameters.action_paramsDict[str,Any]NoAn optional map of action parameters and their values. This will be sent in the request body.Return value:ReturnsActionResponseobjectExample: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_codeResponse Classesclass BaseRestliResponseAll Rest.li request methods of the API client return a response object subclassed from BaseRestliResponse, containing standard response data, along with the original, raw response object.PropertiesTypeDescriptionstatus_codeintResponse status codeurlstrThe final URL location of the responseheadersCaseInsensitiveDictA case-insensitive dictionary of response headersresponseResponseThe raw requests.Response objectclass PagingPaging metadata classPropertiesTypeDescriptionstartintThe start index of returned results (zero-based index)countintThe number of results returned in the responsetotalintThe total number of results availableclass GetResponseBase class:BaseRestliResponsePropertiesTypeDescriptionentityUnion[Dict[str,Any], str, int, bool]The representation (typically a dictionary) of the retrieved entity, decoded from the json-encoded response contentclass BatchGetResponseBase class:BaseRestliResponsePropertiesTypeDescriptionresultsDict[str,Any]A map of entities that were successfully retrieved, with the key being the encoded entity id, and the value being a dictionary representing the entitystatusesDict[str,int]A map of entities and status code, with the key being the encoded entity id, and the value being the status code number value.errorsDict[str,Any]A map containing entities that could not be successfully fetched, with the key being the encoded entity id, and the value being the error response.class CollectionResponseBase class:BaseRestliResponsePropertiesTypeDescriptionelementsList[Dict[str,Any]]The list of entities returned in the responsepagingPagingOptional paging metadata objectmetadataAnyOptional response metadata objectclass BatchFinderResponseBase class:BaseRestliResponsePropertiesTypeDescriptionresultsList[BatchFinderResult]The list of finder results, in the same order as the requested batch finder search criteria listclass BatchFinderResultPropertiesTypeDescriptionelementsList[Dict[str,Any]]The list of entities found for the corresponding finder criteriapagingPagingOptional paging metadata objectmetadataAnyOptional response metadata objecterrorAnyOptional error details if finder call failedisErrorboolFlag if this finder call experienced an errorclass CreateResponseBase class:BaseRestliResponsePropertiesTypeDescriptionentity_idstrThe reduced-encoded entity id.decoded_entity_idUnion[str, Dict[str,Any]]The decoded entity id.entityDict[str,Any]Optional created entity. Some APIs support returning the created entity to eliminate the need for a subsequent GET call.class BatchCreateResponseBase class:BaseRestliResponsePropertiesTypeDescriptionelementsList[BatchCreateResult]The list of batch create results, corresponding to the order of theentitiesrequest parameterclass BatchCreateResultPropertiesTypeDescriptionstatusintThe status code of the individual create callidstrThe id of the created entityerrorAnyError details if the create call experienced an errorclass UpdateResponseBase class:BaseRestliResponsePropertiesTypeDescriptionentityDict[str,Any]Optional entity after the update. Some APIs support returning the updated entity to eliminate the need for a subsequent GET call.class BatchUpdateResponseBase class:BaseRestliResponsePropertiesTypeDescriptionresultsDict[str,BatchUpdateResult]The results map where the keys are the encoded entity ids, and the values are the individual update call results, which includes the status code.class BatchUpdateResultPropertiesTypeDescriptionstatusintThe status code of the individual update callclass BatchDeleteResponseBase class:BaseRestliResponsePropertiesTypeDescriptionresultsDict[str,BatchDeleteResult]The results map where the keys are the encoded entity ids, and the values are the individual delete call results, which includes the status code.class BatchDeleteResultPropertiesTypeDescriptionstatusintThe status code of the delete callclass ActionResponseBase class:BaseRestliResponsePropertiesTypeDescriptionvalueAnyThe action response valueclass AuthClientWhile we recommend using any of several popular, open-source libraries for robustly managing OAuth 2.0 authentication, we provide a basic Auth Client as a convenience for testing APIs and getting started.Constructorfromlinkedin_api.clients.auth.clientimportAuthClientauth_client=AuthClient(client_id=MY_CLIENT_ID,client_secret=MY_CLIENT_SECRET,redirect_url=MY_REDIRECT_URL)ParameterTypeRequired?Descriptionclient_idstrYesClient ID of your developer application. This can be found on your application auth settings page in the Developer Portal.client_secretstrYesClient secret of your developer application. This can be found on your application auth settings page in the Developer Portal.redirect_urlstrNoIf your integration will be using the authorization code flow to obtain 3-legged access tokens, this should be provided. This redirect URL must match one of the redirect URLs configured in the app auth settings page in the Developer Portal.PropertiesPropertyDescriptionsessionThe session object used for making http requests. This is exposed to allow for additional configuration (e.g. adding custom request/response event hooks).Methodsgenerate_member_auth_url (scopes, state=None)Generates the member authorization URL to direct members to. Once redirected, the member will be presented with LinkedIn's OAuth consent page showing the OAuth scopes your application is requesting on behalf of the user.Parameters:ParameterTypeRequired?DescriptionscopesList[str]YesAn array of OAuth scopes (3-legged member permissions) your application is requesting on behalf of the user.statestrNoAn optional string that can be provided to test against CSRF attacks.Return value:The member authorization URL stringexchange_auth_code_for_access_token (code)Exchanges an authorization code for a 3-legged access token. After member authorization, the browser redirects to the provided redirect URL, setting the authorization code on thecodequery parameter.Parameters:ParameterTypeRequired?DescriptioncodestrYesThe authorization code to exchange for an access tokenReturn value:Returns anAccessToken3LResponseobjectexchange_refresh_token_for_access_token (refresh_token)Exchanges a refresh token for a new 3-legged access token. This allows access tokens to be refreshed without having the member reauthorize your application.Parameters:ParameterTypeRequired?Descriptionrefresh_tokenstrYesThe authorization code to exchange for an access tokenReturn value:Returns aRefreshTokenExchangeResponseobjectget_two_legged_access_token ()Use client credential flow (2-legged OAuth) to retrieve a 2-legged access token for accessing APIs that are not member-specific. Developer applications do not have the client credential flow enabled by default.Parameters:NoneReturn value:Returns anAccessToken2LResponseobjectintrospect_access_token (access_token)Introspect a 2-legged, 3-legged or Enterprise access token to get information on status, expiry, and other details.Parameters:ParameterTypeRequired?Descriptionaccess_tokenstrYesA 2-legged, 3-legged or Enterprise access token.Return value:Returns anIntrospectTokenResponseobjectResponse Classesclass BaseAuthResponseAll request methods of the AuthClient return a response object subclassed from BaseAuthResponse, containing standard response data, along with the original, raw response object.PropertiesTypeDescriptionstatus_codeintResponse status codeurlstrThe final URL location of the responseheadersCaseInsensitiveDictA case-insensitive dictionary of response headersresponseResponseThe raw requests.Response objectclass AccessToken3LResponseBase class:BaseAuthResponsePropertiesTypeDescriptionaccess_tokenstrThe 3-legged access tokenexpires_inintThe TTL of the access token, in secondsrefresh_tokenstrThe refresh token value. This is only present if refresh tokens are enabled for the application.refresh_token_expires_inNumberThe TTL of the refresh token, in seconds. This is only present if refresh tokens are enabled for the application.scopestrA comma-separated list of scopes authorized by the member (e.g. "r_liteprofile,r_ads")class AccessToken2LResponseBase class:BaseAuthResponsePropertiesTypeDescriptionaccess_tokenstrThe 2-legged access tokenexpires_inintThe TTL of the access token, in secondsclass RefreshTokenExchangeResponseBase class:BaseAuthResponsePropertiesTypeDescriptionaccess_tokenstrThe 3-legged access tokenexpires_inintThe TTL of the access token, in secondsrefresh_tokenstrThe refresh token value. This is only present if refresh tokens are enabled for the application.refresh_token_expires_inNumberThe TTL of the refresh token, in seconds. This is only present if refresh tokens are enabled for the application.class IntrospectTokenResponseBase class:BaseAuthResponsePropertiesTypeDescriptionactivestrFlag whether the token is a valid, active token.auth_typestrThe auth type of the token ("2L", "3L" or "Enterprise_User")authorized_atstrEpoch time in seconds, indicating when the token was authorizeclient_idstrDeveloper application client IDcreated_atintEpoch time in seconds, indicating when this token was originally issuedexpires_atintEpoch time in seconds, indicating when this token will expirescopestrA string containing a comma-separated list of scopes associated with this token. This is only returned for 3-legged member tokens.statusstrThe token status, which is an enum string with values "revoked", "expired" or "active"List of dependenciesThe following table is a list of production dependencies.Component NameLicenseLinkedModifiedrequestsApache 2.0StaticNo