如何修复Python调用LinkedIn API更新资料时的PATCH请求错误
修复LinkedIn API调用时的PATCH方法错误
问题场景
尝试用以下Python代码调用LinkedIn API更新个人资料的标题(headline)和简介(summary),已配置好权限,但收到错误:
"message": "java.lang.IllegalArgumentException: No enum constant com.linkedin.restli.common.HttpMethod.PATCH",
原代码:
import requests access_token = "xxx" profile_id = "me" # "me" refers to the currently authenticated user's profile new_headline = "New Headline Text" new_summary = "New Summary Text" def update_profile(): endpoint_url = f"https://api.linkedin.com/v2/me" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } payload = { "headline": new_headline, "summary": new_summary } response = requests.patch(endpoint_url, headers=headers, json=payload) if response.status_code == 200: print("Profile updated successfully.") else: print("Error updating profile.") print(response.text) if __name__ == '__main__': update_profile()
错误原因
LinkedIn API的/v2/me端点不支持PATCH请求,且个人资料的headline和summary属于独立资源,需要通过各自的专用端点进行更新,同时请求体必须符合LinkedIn的多语言格式规范。
修正方案
改用PUT方法,针对headline和summary分别调用专用端点,并调整请求体结构以满足API要求:
import requests access_token = "xxx" # 根据实际需求调整语言和国家代码 locale = {"country": "US", "language": "en"} new_headline = "New Headline Text" new_summary = "New Summary Text" def update_headline(): endpoint = "https://api.linkedin.com/v2/headlines/me" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } payload = { "headline": { "localized": {f"{locale['language']}_{locale['country']}": new_headline}, "preferredLocale": locale } } return requests.put(endpoint, headers=headers, json=payload) def update_summary(): endpoint = "https://api.linkedin.com/v2/summaries/me" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } payload = { "summary": { "localized": {f"{locale['language']}_{locale['country']}": new_summary}, "preferredLocale": locale } } return requests.put(endpoint, headers=headers, json=payload) if __name__ == '__main__': headline_resp = update_headline() if headline_resp.status_code in (200, 201): print("标题更新成功") else: print("标题更新失败:") print(headline_resp.text) summary_resp = update_summary() if summary_resp.status_code in (200, 201): print("简介更新成功") else: print("简介更新失败:") print(summary_resp.text)
关键修改说明
- 端点替换:使用
/v2/headlines/me和/v2/summaries/me分别处理标题和简介的更新,这是LinkedIn API指定的专用资源路径 - 请求方法变更:改用PUT方法,LinkedIn的这类资源端点支持PUT操作来创建或更新内容
- 请求体结构调整:按照API要求添加本地化字段和首选区域设置,确保内容符合多语言存储规范
- 分开处理字段:由于headline和summary是独立资源,需要分别发起请求进行更新
内容的提问来源于stack exchange,提问作者Chakra
相关产品推荐
相关产品推荐

