使用Python调用LinkedIn API获取关注者数遇500错误求助
解决LinkedIn API调用organizationalEntityFollowerStatistics返回500错误的可行方向
1. 修正授权Scope,确保包含r_organization_followers
你当前获取授权码的scope仅包含r_organization_social rw_organization_admin,但获取关注者统计数据必须拥有r_organization_followers权限。即便应用已申请该权限,授权时未在scope中声明会导致访问令牌缺少对应权限,进而引发服务端错误。修改scope部分代码:
scope = 'r_organization_social rw_organization_admin r_organization_followers' encoded_scope = urllib.parse.quote(scope)
重新获取授权码和访问令牌后再尝试调用接口。
2. 使用URN格式指定组织ID
LinkedIn API的organizationalEntity参数要求传入URN格式的组织标识,而非纯数字ID。修改请求URL:
organization_urn = f'urn:li:organization:{organization_id}' followers_url = f'https://api.linkedin.com/rest/organizationalEntityFollowerStatistics?q=organizationalEntity&organizationalEntity={organization_urn}'
这是最常见的参数格式错误,极易导致服务端解析失败返回500。
3. 补充完整请求头信息
确保请求头包含Accept字段,明确指定响应格式,避免服务端解析歧义:
headers = { 'Authorization': f'Bearer {access_token}', 'X-Restli-Protocol-Version': '2.0.0', 'LinkedIn-Version': '202406', 'Accept': 'application/json' }
4. 替代方案:直接从组织信息接口获取关注者数量
如果统计端点持续报错,可以尝试从organizations接口直接提取followerCount字段,无需调用统计接口:
org_url = 'https://api.linkedin.com/rest/organizations?q=vanityName&vanityName=CompanyName&projection=(id,followerCount)' org_response = requests.get(org_url, headers=headers) org_data = org_response.json() follower_count = org_data['elements'][0]['followerCount'] print(f'Follower Count: {follower_count}')
通过projection参数指定只返回需要的字段,同时提升请求效率。
5. 排查组织ID有效性
确认获取的组织ID属于你有权限访问的企业主页:
- 检查
org_response.json()返回的elements中,组织名称、域名等信息是否匹配目标主页 - 若返回多个组织结果,确保选择的是正确的ID
6. 检查LinkedIn API服务状态
登录LinkedIn开发者平台,查看服务状态公告,确认是否存在organizationalEntityFollowerStatistics端点的故障或维护通知。
内容的提问来源于stack exchange,提问作者HoneyBadger
相关产品推荐
相关产品推荐

