<目次>
(1) LinkedIn APIの使い方について(PythonでAPIコール疎通させるまで)
(1-1) STEP1:【任意】企業・団体ページの作成
(1-2) STEP2:Appの作成
(1-3) STEP3:AppのVerify
(1-4) STEP4:Appの「Auth」タブの確認/設定
(1-5) STEP5:Appの「Products」タブの確認/設定
(1-6) STEP6:認証コードの取得(Python)
(1-7) STEP7:API疎通チェック(Python)
(1) LinkedIn APIの使い方について(PythonでAPIコール疎通させるまで)
LinkedIn APIの使い方という事で、Python言語でAPIコールを疎通させるまでに必要なステップをご紹介します。
(1-1) STEP1:【任意】企業・団体ページの作成




(1-2) STEP2:Appの作成





(1-3) STEP3:AppのVerify




↓


↓

(1-5) STEP5:Appの「Products」タブの確認/設定





(1-6) STEP6:認証コードの取得(Python)
●STEP6-1:コード(code)の取得

(サンプルプログラム)
# 必要なパッケージ: python -m pip install requests import requests, secrets url = requests.Request( 'GET', 'https://www.linkedin.com/oauth/v2/authorization', params = { 'response_type': 'code', # Always should equal to fixed string "code" # ご自身のAppのClientID 'client_id': 'XXXXXX', # ログインしたユーザーが認証後にリダイレクトされるURIを指定 # (備考) # ・この値は「OAuth 2.0 Authorized Redirect URLs」の値のいずれかと一致する必要あり # ・ご自身で所有するローカルやリモートのサーバ等を指定します。 'redirect_uri': 'http://localhost:8000', # 一意なランダム文字列を指定。 # サーバ側で現在の認証リクエストを識別するために使用します。 # もし値を何にするか困った場合、例えば「secrets.token_hex(8).upper()」のようなモジュールで生成するものありです。 # このstateをサーバで保持する事で、認証済のセッションを識別します。 #'state': secrets.token_hex(8).upper(), 'state' : 'XXXXXX', # リクエストする権限を指定。 # 下記は一例のため、必要に応じて変更。 # ↓付与可能な権限の一覧はこちら # https://docs.microsoft.com/en-us/linkedin/shared/references/migrations/default-scopes-migration#scope-to-consent-message-mapping #'scope': '%20'.join(['r_liteprofile', 'r_emailaddress', 'w_member_social']), 'scope': 'r_liteprofile' }, ).prepare().url # ここまで来たら、サーバ⇒クライアントにURLを送ってOK # 今回はローカル実行のため、サーバ⇒クライアントにURLを送る import webbrowser webbrowser.open(url)



http://localhost:8000/?code=XXXXXXXXXXXX&state=DCEeFWf45A53sdfKef424
●STEP6-2:「access_token」の取得
・①「access_tokenを取得するための下記Pythonプログラムをローカル実行

(サンプルプログラム)
import requests access_token = requests.post( 'https://www.linkedin.com/oauth/v2/accessToken', params = { 'grant_type': 'authorization_code', # 前の手順で取得したcodeをセット 'code': 'XXXXX', # 前の手順のPythonコード中の'redirect_uri'と同じ値にする 'redirect_uri': 'http://localhost:8000', # ご自身のAppのClient ID 'client_id': 'XXXXX', # ご自身のAppのClient Secret 'client_secret': 'XXXXXX', }, ).json()['access_token'] print(access_token)
(1-7) STEP7:API疎通チェック(Python)

import requests import os import oauth2 as oauth from requests.auth import HTTPBasicAuth def main(): response = requests.get( 'https://api.linkedin.com/v2/me', params = { # APIパラメータがあれば追記 }, headers = { 'Authorization': 'Bearer ' + 'XXXXX', # HTTPヘッダーがあれば追記 }, ) res_json = response.json() print(res_json) return res_json if __name__ == "__main__": main()
{'localizedLastName': 'xxxx', 'profilePicture': {'displayImage': 'urn:li:digitalmediaAsset:C5603AQG8r0KSOzwwaA'}, 'firstName': {'localized': {'ja_JP': ' xxxx '}, 'preferredLocale': {'country': 'JP', 'language': 'ja'}}, 'lastName': {'localized': {'ja_JP': 'xxxx'}, 'preferredLocale': {'country': 'JP', 'language': 'ja'}}, 'id': 'XXXXXX', 'localizedFirstName': 'xxxx'}