首页 > 解决方案 > 使用 access_token 向 Facebook 的 Graph API 发出 POST 请求

问题描述

Facebook 关于为 Leadgen 创建测试线索的文档相当乏味。但是,它们提供了一些有用的 cURL 命令,并且似乎可以完成工作:

curl \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/<FORM_ID>/test_leads"

curl \
-F "field_data=[{'name': 'favorite_color?', 'values': ['yellow']}, {'name': 'email', 'values': ['test@test.com']}]" \
-F "custom_disclaimer_responses=[{'checkbox_key': 'my_checkbox', 'is_checked': true}]" \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/<FORM_ID>/test_leads"

就像我说的,这对我有用。但是,我想知道如何使用 Python 的requests库及其post方法提出这个请求。

这是我正在使用的代码:

token = "<MY_TOKEN"
url = "https://graph.facebook.com/<MY_API_VERSION>/<MY_FORM_ID>/test_leads"

r = requests.post(url, headers={'access_token': token})

我似乎无法通过使用 Python("code":100,"error_subcode":33从 Facebook 返回)获得此请求,但使用 cURL 可以正常工作。我可以做些什么来让这个请求使用我的 Python 脚本工作。

编辑:结合我关于如何通过我的 Post 请求传递访问令牌的问题,我将如何传递他们在示例中显示的其他内容,嗯field_data,和custom_disclaimer_responses

EDIT2:如果我使用 URL "https://graph.facebook.com/<MY_API>/<MY_FORM_ID>/test_leads?access_token="+token,请求就会顺利通过。我似乎无法通过标题传递它。

标签: pythonpython-3.xpython-2.7facebook-graph-api

解决方案


为了

curl \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/<FORM_ID>/test_leads"

在python中你可以做

import requests

files = {
    'access_token': (None, 'ACCESS_TOKEN'),
}

response = requests.post('https://graph.facebook.com/API_VERSION/FORM_ID/test_leads', files=files)

为了

curl \
-F "field_data=[{'name': 'favorite_color?', 'values': ['yellow']}, {'name': 'email', 'values': ['test@test.com']}]" \
-F "custom_disclaimer_responses=[{'checkbox_key': 'my_checkbox', 'is_checked': true}]" \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/<FORM_ID>/test_leads"

在python中你可以做

import requests

files = {
    'field_data': (None, '[ {'name': 'favorite_color?', 'values': ['yellow'] }, {'name': 'email', 'values': ['test@test.com'] } ]'),
    'custom_disclaimer_responses': (None, '[ { 'checkbox_key': 'my_checkbox', 'is_checked': 'true' } ]'),
    'access_token': (None, 'ACCESS_TOKEN'),
}

response = requests.post('https://graph.facebook.com/API_VERSION/FORM_ID/test_leads', files=files)

推荐阅读