Accessing Facebook Data with Python: Examples for Post Likes, Views, and Profile Details

Facebook is one of the most popular social media platforms in the world. With over 2 billion monthly active users, it is a treasure trove of data that can be utilized for marketing, research, and analysis. Facebook provides a powerful API that allows developers to access and interact with its data, making it an essential tool for businesses of all sizes.

In this article, we will explore the Facebook API and show you how to use it with Python. We will cover everything from setting up your API key to making requests and parsing responses.

Getting Started

To use the Facebook API, you will need to create a Facebook Developer account and create an app. Follow the steps below to get started:

  1. Create a Facebook Developer account: Go to the Facebook Developer website and sign up for an account. You will need to provide some basic information, including your name and email address.

  2. Create a new app: Once you have created your account, click on the Create App button and choose the platform you want to develop for. For this tutorial, we will be developing for the web.

  3. Set up your API key: After creating your app, you will be given an API key. This key will be used to authenticate your requests to the Facebook API.

Now that you have set up your Facebook Developer account and created an app, you are ready to start using the Facebook API.

Facebook Graph API

Facebook provide a powerful and comprehensive RESTful API known as the Facebook Graph API. The Graph API allows developers to interact with Facebook data, such as users, pages, posts, and more, using HTTP requests.

To use the Facebook Graph API with Python, you can make HTTP requests to the API endpoints using libraries like requests or httplib2, and then parse the JSON responses to extract the data you need. Additionally, there are several third-party libraries available that simplify working with the Facebook Graph API in Python, such as facebook-sdk and python-graph-api.

In this blog, we will use requests library to interact with Facebook Graph API.

Making Requests

  • Install requests library
pip install requests

To make a request to the Facebook API, you will need to provide your API key and the endpoint you want to access. For example, to get information about a specific user, you would use the following code:

import requests

access_token = '<your_access_token>'
user_id = '<user_id>'

url = f'https://graph.facebook.com/{user_id}?access_token={access_token}'

response = requests.get(url)

print(response.json())

In this example, we are using the requests library to send a GET request to the Facebook API. We are passing in our API key and the user ID we want to access. The response from the API is returned as a JSON object, which we can parse using the json() method.

Handling Responses

When you make a request to the Facebook API, the response will be returned as a JSON object. To parse this object, you can use the json() method provided by the requests library.

For example, if you want to get the name of a user, you can use the following code:

import requests

access_token = '<your_access_token>'
user_id = '<user_id>'

url = f'https://graph.facebook.com/{user_id}?access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['name'])

In this example, we are accessing the name field of the JSON object returned by the Facebook API. We are using the json() method to parse the response and then accessing the name field using dictionary notation.

Explore Facebook Graph API

Here are some examples to get post likes, views, comments, and other information using the Facebook API and Python:

Getting Profile Details

To get details about a Facebook profile, such as the name, ID, and profile picture, you can use the following code:

import requests

access_token = '<your_access_token>'
user_id = '<user_id>'

url = f'https://graph.facebook.com/{user_id}?fields=name,id,picture&access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data)

In this example, we are accessing the user object to get the name, ID, and profile picture. We are using the fields parameter to specify the fields we want to retrieve, and then accessing those fields in the response.

What is user_id and how to get user_id?

The user_id is a unique identifier for a Facebook user, which is assigned to each user when they create a Facebook account.

To get the user_id of a Facebook user, you can follow these steps:

  1. Go to the Facebook profile of the user you want to get the user_id for.
  2. Look at the URL in your browser’s address bar.
  3. The user_id is the string of numbers that comes after the "facebook.com/” part of the URL.

For example, if the URL is https://www.facebook.com/skillshats, the user_id for this user would be “skillshats”.

Alternatively, you can use the Facebook Graph API to get the user_id of a user programmatically. Here’s an example:

import requests

access_token = '<your_access_token>'
user_name = '<your_user_name>'

url = f'https://graph.facebook.com/{user_name}?access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['id'])

In this example, we are accessing the /{user_name} endpoint of the Facebook Graph API to get the ID of the user. We are passing the user_name as a parameter in the URL, and then accessing the id field of the response. Note that you will need to have the proper access token for this request to work.

Once you have the user_id, you can use it in your code to retrieve information about the user or their posts.

Getting Posts

To get a list of posts from a Facebook page or profile, you can use the following code:

import requests

access_token = '<your_access_token>'
page_id = '<page_id>'

url = f'https://graph.facebook.com/{page_id}/posts?access_token={access_token}'

response = requests.get(url)

data = response.json()

for post in data['data']:
    print(post['message'])

In this example, we are accessing the posts endpoint of the page object to get a list of all the posts. We are then iterating over each post in the data field of the response and printing the post message.

What is page_id and how to get page_id?

The page_id is a unique identifier for a Facebook Page, which is a public profile on Facebook that can be used to represent a business, organization, public figure, or other entity.

To get the page_id, you need to first have a Facebook account and be an admin or editor of the Page. Once you have that, you can follow these steps to get the page_id:

Go to the Facebook Page you want to get the page_id for.

  1. Click on the About tab.
  2. Scroll down to the bottom of the page and look for the Facebook Page ID section.
  3. The page_id is the number listed in this section.

Alternatively, you can also get the page_id programmatically using the Facebook API. Here’s an example:

import requests

access_token = '<your_access_token>'
page_name = '<your_page_name>'

url = f'https://graph.facebook.com/{page_name}?access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['id'])

In this example, we are accessing the /{page_name} endpoint of the Facebook Graph API to get the ID of the page. We are passing the page_name as a parameter in the URL, and then accessing the id field of the response. Note that you will need to have the proper access token for this request to work.

Once you have the page_id, you can use it in your code to retrieve information about the Page or its posts.

Getting Post Likes

To get the number of likes on a post, you can use the following code:

import requests

access_token = '<your_access_token>'
post_id = '<post_id>'

url = f'https://graph.facebook.com/{post_id}?fields=likes.summary(true)&access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['likes']['summary']['total_count'])

In this example, we are accessing the likes field of the post object and then accessing the summaryfield to get the total number of likes.

Getting Post Views

To get the number of views on a post, you can use the following code:

import requests

access_token = '<your_access_token>'
post_id = '<post_id>'

url = f'https://graph.facebook.com/{post_id}/insights/post_impressions_unique?access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['data'][0]['values'][0]['value'])

In this example, we are using the insights endpoint to get the number of unique post impressions. We are accessing the data field of the response, which contains an array of objects, and then accessing the values field to get the most recent value.

Getting Post Comments

To get the number of comments on a post, you can use the following code:

import requests

access_token = '<your_access_token>'
post_id = '<post_id>'

url = f'https://graph.facebook.com/{post_id}/comments?summary=true&access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['summary']['total_count'])

In this example, we are accessing the comments endpoint of the post object and using the summary parameter to get the total number of comments.

Getting Post Insights

To get more detailed insights about a post, you can use the following code:

import requests

access_token = '<your_access_token>'
post_id = '<post_id>'

url = f'https://graph.facebook.com/{post_id}/insights?metric=post_impressions_unique,post_clicks,post_engaged_users,post_reactions_like_total&access_token={access_token}'

response = requests.get(url)

data = response.json()

print(data['data'])

In this example, we are using the insights endpoint to get a variety of metrics for the post, including unique impressions, clicks, engaged users, and reactions. We are accessing the data field of the response, which contains an array of objects, and then iterating over each object to get the metric values.

Conclusion

Using the Facebook API and Python, you can easily access and analyze a wide range of data from Facebook, including posts and profile details. By incorporating this data into your marketing, research, and analysis efforts, you can gain valuable insights into user behavior and engagement on the platform.

Explore More Python Posts

Using Twitter API with Python: Getting Tweets & Insights

Learn how to use the Twitter API with Python to get tweet information and insights. Extract valuable data for businesses and researchers with ease.

Read More
Python Design Patterns: Examples and Best Practices

Learn about Python design patterns with examples and discover best practices for writing maintainable and scalable code.

Read More
How to Use the YouTube API with Python: A Step-by-Step Guide

Learn how to access and retrieve information from YouTube using Python and the YouTube API. Get code examples and step-by-step instructions for impor…

Read More
Top 3 Python Frameworks for Web Development

Discover the most popular and efficient Python frameworks for building dynamic web applications. Get started today!

Read More
Debugging Made Easy with IPDB - The Python Debugger

Revolutionize the way you debug your Python code with IPdb, the advanced interactive debugger that streamlines your debugging process. Say goodbye to…

Read More
Optimize Python Requests for Faster Performance

Learn how to improve the speed of Python requests with connection pooling, async programming, compression, caching, and keep-alive. Boost the perform…

Read More