Share Post Using Facebook API

Minahil Faisal
 import logging
import os
from typing import Optional
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

FACEBOOK_API_URL = "https://graph.facebook.com/v12.0/me/feed"
ACCESS_TOKEN = os.environ['FACEBOOK_ACCESS_TOKEN']

class PostData(BaseModel):
    message: str
    link: Optional[str] = None

@app.post("/share")
def share_to_facebook(post_data: PostData):
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"

About this template

An app that shares a post to your page feed using Facebook API. This app uses the FastAPI to create an endpoint to call the Facebook API for sharing a post on your page. A facebook access token for the page will be needed to make the API call. The permission scopes you will need for the access token are `pages_read_engagement` and `pages_manage_posts permissions` as an admin of the page you are posting to. A link to another facebook can also be provided to share that post with a caption on your page.

Introduction to the Share Post Using Facebook API Template

Welcome to the Share Post Using Facebook API template! This template is designed to help you quickly set up an application that can share posts to a Facebook page using the Facebook API. It leverages FastAPI to create an endpoint that interacts with the Facebook API, allowing you to post messages and links to your page's feed. Before you can use this template, you'll need to have access to a Facebook page and obtain the necessary access token with the correct permissions.

Clicking Start with this Template

To begin using this template, simply click on the "Start with this Template" button. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy or paste any code manually.

Initial Setup: Adding Environment Secrets

Before you can share posts to Facebook, you need to set up an environment secret for your Facebook access token. Here's how to obtain and set up your access token:

  • Go to the Facebook Developer portal and create a new app if you haven't already.
  • Under your app's settings, navigate to the "Access Tokens" section.
  • Generate a new access token with the `pages_read_engagement` and `pages_manage_posts` permissions.
  • Copy the access token provided by Facebook.
  • In the Lazy Builder interface, go to the Environment Secrets tab.
  • Create a new secret with the key `FACEBOOK_ACCESS_TOKEN` and paste the access token you copied as the value.

With the environment secret set, your app will be able to authenticate with the Facebook API.

Test: Pressing the Test Button

Once you've set up your environment secret, press the "Test" button to begin the deployment of your app. The Lazy CLI will handle the deployment process, and you won't need to install any libraries or set up your environment.

Using the App

After pressing the "Test" button, Lazy will provide you with a dedicated server link to use the API. You can interact with your new app by sending HTTP requests to the provided endpoints. Additionally, you'll receive a link to the FastAPI documentation, which will show you all the available endpoints and how to use them.

Here's a sample request to share a post to Facebook using the `/share` endpoint:


POST /share HTTP/Content-Type: application/json
{
  "message": "Hello, Facebook!",
  "link": "https://example.com"
}

And a sample response indicating success:


{
  "message": "Post shared successfully to Facebook."
}

Integrating the App

If you wish to integrate this app with other services or frontends, you can use the server link provided by Lazy to send requests from your external tool. Ensure that you handle the authentication correctly by including the access token in your requests.

For example, if you're integrating with a frontend application, you can make an AJAX call to the `/share` endpoint using the server link as the base URL.

By following these steps, you should now have a fully functional app that can share posts to a Facebook page using the Facebook API. Remember to handle your access token securely and adhere to Facebook's API usage policies.

Category
Technology
Last published
July 26, 2024

More templates like this

SecureUserAuthenticator

Develop a secure User Authentication system for users to register, log in, and manage their profiles, laying the foundation for user-specific data management and permissions in the CMS.

Laravel
Python
Flask
Javascript

Simple Multiplayer Telegram game

This app is a simple frontend for a game where users can upvote and downvote the most popular word in their country, learn about the flags of other countries, and view what other people voted for on a leaderboard.

Telegram
Python
Javascript

MP3ify: Youtube to MP3 Converter

A web application that allows users to download YouTube videos from URLs and provides the option to convert them to MP3 format.

Python
Flask
Home
/
Share Post Using Facebook API