How to load data from Facebook Ads to PostgreSQL

You can pull your data out of Facebook Ads through the Ads Insights API. The Insights API provides access to analytics and reporting functionality and the way you interact with your data is by requesting reports where you define exactly the data and its granularity that you need. As in the case of Google, Facebook also exposes a very rich set of APIs that you can use for every aspect of your advertising needs, from creating ads programmatically to see how your campaigns perform.

When it comes to Facebook Ads, there are various metrics you can track to measure the performance and effectiveness of your advertising campaigns. Those include Impressions, Reach, Clicks and Click-through-rates. These metrics provide valuable insights into the impact of your ads and help you make data-driven decisions to optimize your advertising strategy.

Why extract Facebook Ad data?

Facebook Ads provides robust capabilities for analyzing ad spend, campaign performance, and conversion rate. By leveraging the available data and metrics, you can gain valuable insights into the effectiveness of your advertising efforts. Here's how Facebook Ads can help you analyze these aspects:

Ad Spend Analysis:

  • Cost Metrics: Facebook provides detailed cost metrics, including Cost per Click (CPC), Cost per Mille (CPM), and Cost per Action (CPA). By analyzing these metrics, you can evaluate the efficiency and cost-effectiveness of your ad spend.
  • Budget Allocation: Facebook allows you to set budgets at the campaign, ad set, and ad levels. Analyzing the distribution of your ad spend across different campaigns or ad sets helps you identify areas where you're investing the most and optimize your budget allocation accordingly.

Campaign Performance Analysis:

  • Key Performance Indicators (KPIs): Facebook Ads offers various KPIs to measure campaign performance metrics, including Impressions, Reach, Clicks, CTR, and Engagement. Analyzing these metrics helps you evaluate the overall effectiveness and impact of your campaigns.
  • Ad Creative Analysis: By comparing the performance of different ad creatives, such as images, videos, or copy variations, you can identify which elements resonate best with your target audience. This analysis enables you to optimize your creative strategy for improved campaign performance.

In this post we’ll focus only on how to extract data out of Facebook Ads, for further information on what else can be performed through the Facebook Ads related APIs, you can check the documentation of the Marketing API.

Before you start doing anything, have a read on how to activate and manage your developer account from your Facebook page. And make sure that you understand the security-related concepts of the Facebook Marketing API.

In general, access to the API happens mainly through the SDKs that Facebook offers. Officially, SDKs for PHP and Python are supported, while there are also a number of community-supported SDKs for languages like R, JavaScript, and Ruby.

The Facebook Marketing API is a RESTful web API and thus can also be accessed by performing requests directly to the appropriate endpoints. As a RESTful API, interacting with it can be achieved by using tools like CURL or Postman or by using HTTP clients for your favorite language or framework. A few suggestions:

  • Apache HttpClient for Java
  • Spray-client for Scala
  • Hyper for Rust
  • Ruby rest-client
  • Python http-client

As everything in Facebook, Ads and their statistics are part of the Graph API, which you can interact with also using the Graph Explorer, and there’s a special Edge that you can use to request ad’s statistics, it’s the insights edge.

Insights can be access from the following list of edges:

The response from each contains information belonging to the ad object for which insights are queried.

For example, let’s assume that you would like to extract all stats related to your account. You could do this by executing the following request using CURL.

-F 'level=campaign'
-F 'fields=[]'
-F 'access_token=<ACCESS_TOKEN>'<CAMPAIGN_ID>/insights
curl -G
-d 'access_token=<ACCESS_TOKEN>'
curl -G
-d 'access_token=<ACCESS_TOKEN>'

Data can be returned in either xls or csv format and when the report is ready based on your request you can access it from a URL like the following:


Get Real-time Streams of your Facebook Ads Stats

It’s also possible to create a real-time data infrastructure for fetching data from Facebook Ads and loading them into your data warehouse repository. You can do that by subscribing to real-time updates to receive API updates with webhooks. With the proper infrastructure, you can have an almost real-time feed of data into your repository and ensure that it will always be up to date with the latest data.

Facebook Ads exposes a very rich API which offers you the opportunity to get very granular data about your Facebook ads account activities and use it for analytic and reporting purposes. This richness comes with a price though, a large number of complex resources that have to be handled through an also complex protocol.

With Facebook Ads, you can create targeted adverts to reach different audiences and meet your business goals. These adverts can appear in different locations on Facebook, like the Newsfeed or the right column of Facebook on the desktop. Just like Google AdWords, Facebook Ads is a Real-Time Bidding system where advertisers compete to display their advertising material. Programmatic and instantaneous auctions are performed, similar to how financial markets operate. Among the benefits of Facebook Ads, are:

  • Reach – potentially you can reach more than 1 billion active Facebook users.
  • Any budget – You can start with any budget, although you have to be aware of the Real-Time Bidding nature of Facebook Ads, which means that the effectiveness of your campaigns is linked to what your competitors are also willing to pay.
  • Pay-per-click – advertisers pay only for ads that have been clicked by the user.

Facebook Ads Data Preparation for PostgreSQL

As more companies utilize Facebook ads across multiple platforms, there is a growing need to centralize and consolidate data from these platforms into a single data store. This allows them to obtain a comprehensive overview of the data generated from various sources. Popular options for data stores include Microsoft SQL Server, Snowflake, and PostgreSQL. By consolidating marketing data ingested from ads platforms and various SaaS tools in a centralized location, companies can efficiently analyze and derive insights from the combined data, enabling more informed decision-making and a holistic view of their advertising efforts.

To populate a PostgreSQL database instance with data, first, you need to have a well-defined data model or schema that describes the data. As a relational database, PostgreSQL organizes data around tables.

Each table is a collection of columns with a predefined data type as an integer or VARCHAR. PostgreSQL, like any other SQL database, supports a wide range of different data types.

A typical strategy for loading data from Facebook Ads to PostgreSQL database is to create a schema where you will map each API endpoint to a table. Each key inside the Facebook Ads API endpoint response should be mapped to a column of that table and you should ensure the right conversion to a PostgreSQL compatible data type. For example, if an endpoint from Facebook Ads returns a value as String, you should convert it into a VARCHAR with a predefined max size or TEXT data type. tables can then be created on your database using the CREATE SQL statement.

Of course, you will need to ensure that as the data types from the Facebook Ads API might change, you will adapt your database tables accordingly, there’s no such thing as automatic data typecasting.

After you have a complete and well-defined data model or schema for PostgreSQL, you can move forward and start loading your data into the database.

About PostgreSQL

PostgreSQL or simply Postgres is one of the most well-known, popular, and well-supported databases. It can be used for different workloads, from simple single-machine applications to large-scale data warehousing scenarios.

PostgreSQL is ACID-compliant, transactional, and has one of the richest feature sets; including materialized views, triggers, foreign keys, stored procedures, and an architecture that encourages its extensibility.

Especially its last characteristic has made PostgreSQL one of the most forked databases. Amazon Redshift is based on an earlier version of PostgreSQL as other database systems like Citus Data and Greenplum Database.

All the above characteristics of PostgreSQL, a rich set of aggregation functions, the ability to define both simple and materialized views, the support for user-defined functions, and the ability to scale to pretty large datasets, make it an ideal database for analytics-related tasks.

Let’s see what it takes to populate and maintain a PostgreSQL database with data for analytics and business intelligence purposes.

Load data from Facebook Ads to PostgreSQL

Once you have defined your schema and you have created your tables with the proper data types, you can start loading your Facebook data into your database.

The most straightforward way to insert data into a PostgreSQL database is by creating and executing INSERT statements. With INSERT statements, you will be adding data row-by-row directly to a table. It is the most basic and straightforward way of adding data into a table but it doesn’t scale very well with larger data sets.

The preferred way for adding larger datasets into a PostgreSQL database is by using the COPY command. COPY is copying data out of a file on a file system that is accessible by the PostgreSQL instance, in this way much larger datasets can be inserted into the database in less time.

You should also consult the documentation of PostgreSQL on how to populate a database with data. It includes a number of very useful best practices on how to optimize the process of loading data into your PostgreSQL database.

COPY requires physical access to a file system in order to load data. Nowadays, with cloud-based, fully managed databases, getting direct access to a file system is not always possible. If this is the case and you cannot use a COPY statement, then another option is to use PREPARE together with INSERT, to end up with optimized and more performant INSERT queries.

Updating your Facebook Ads data on PostgreSQL

As you will be generating more data on Facebook Ads, you will need to update your older data on PostgreSQL. This includes new records together with updates to older records that for any reason have been updated on Facebook Ads.

You will need to periodically check Facebook Ads for new data and repeat the process that has been described previously while updating your currently available data if needed. Updating an already existing row on a PostgreSQL table is achieved by creating UPDATE statements.

Another issue that you need to take care of is the identification and removal of any duplicate records on your database. Either because Facebook Ads does not have a mechanism to identify new and updated records or because of errors on your data pipelines, duplicate records might be introduced to your database.

In general, ensuring the quality of the data that is inserted in your database is a big and difficult issue and PostgreSQL features like TRANSACTIONS can help tremendously, although they do not solve the problem in the general case.

The best way to load data from Facebook Ads to PostgreSQL

So far we just scraped the surface of what you can do with PostgreSQL and how to load data into it. Things can get even more complicated if you want to integrate data coming from different sources.

Are you striving to achieve results right now?

Instead of writing, hosting, and maintaining a flexible data infrastructure use RudderStack that can automate ETL processes into data storage tools and handle everything for you.

RudderStack with one click integrates with sources or services, creates analytics-ready data, and syncs your Facebook Ads to PostgreSQL using a built-in PostgreSQL integration that you can use right away. Check out RudderStack's Facebook Ads to PostgreSQL integration.

Sign Up For Free And Start Sending Data

Test out our event stream, ELT, and reverse-ETL pipelines. Use our HTTP source to send data in less than 5 minutes, or install one of our 12 SDKs in your website or app.

Don't want to go through the pain of direct integration? RudderStack's Facebook Ads integration makes it easy to send data from Facebook Ads to PostgreSQL.