DEV Community

Cover image for Automate Facebook APIs with Python ( Publish a Post on Facebook using Python )
Hansana Ranaweera
Hansana Ranaweera

Posted on

Automate Facebook APIs with Python ( Publish a Post on Facebook using Python )

Here we are going to discuss how to publish a post on Facebook with Facebook graph API using python

First We are Going to Getting Know about What is Facebook Graph APIs
The Facebook Graph API exposes URL endpoints to which you can make GET and POST calls to interact with your Facebook page or upload data and posts to your Facebook account. The Graph API is the primary way for apps to read and write to the Facebook social graph.
using Facebook Graph API,

  1. Read the messages on your timeline,
  2. Send messages,
  3. Read posts,
  4. Create posts, edit posts or even delete posts and etc…

Before You Start, You will need ( see video tutorial ):

  1. Register as a Facebook Developers
  2. Create a Facebook App
  3. Open the Graph Explorer tool ( this tool lets you make calls to Facebook’s Graph API)
  4. Get brief understanding of the structure of the Facebook Social Graph from our Graph API Overview guide

** Main Step 01 **( Create a Facebook App )
Image description
Image description
Image description

** Main Step 02 ** ( Get your Facebook Page Access Tokens )
see this video
Image description

** Main Step 03 ** ( Send Request Using Python )

We will be using the requests library for sending the HTTP requests. Requests allow you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs or to form-encode your PUT & POST data — but nowadays, just use the json method!

python -m pip install requests
Enter fullscreen mode Exit fullscreen mode
  1. You will also need a page ID — for the Facebook page you would like to post to. You can get your page ID directly from your Facebook page, under the “About” tab. Copy this ID and paste it into your code.

Image description

  1. This is the code for creating a post
import requests
#Your Access Keys
page_id_1 = 123456789
# Your Page Access Token
facebook_access_token_1 = ‘Your Page Access Token’
# Post Content as Text
msg = ‘hi buddy’
post_url = ‘{}/feed'.format(page_id_1)
payload = {
‘message’: msg,
‘access_token’: facebook_access_token_1
r =, data=payload)
Enter fullscreen mode Exit fullscreen mode

Thank you!

Discussion (0)