Pricing
Log in

BY RUDDERSTACK TEAM

How to load data from Facebook Ads to PostgreSQL

01. Extract Data from Facebook Ads

  • 01. Extract Data from Facebook Ads
  • 02. Prepare Data
  • 03. Load Data
  • 04. Update Data
  • 05. Extract Data

Try RudderStack for free

Sign up for RudderStack for free.

This post helps you with loading your data from Facebook Ads to PostgreSQL. If you are looking to get analytics-ready data without the manual hassle you can integrate Facebook Ads to PostgreSQL with RudderStack, so you can focus on what matters, getting value out of your advertising data.

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.

Extract data from Facebook Ads

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 advertisement needs, from creating ads programmatically to see how your campaigns perform.

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. 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.

You can also find more if you do some research on places like GitHub. 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.

SH
curl
-F 'level=campaign'
-F 'fields=[]'
-F 'access_token=<ACCESS_TOKEN>'
https://graph.facebook.com/v2.5/<CAMPAIGN_ID>/insights
curl -G
-d 'access_token=<ACCESS_TOKEN>'
https://graph.facebook.com/v2.5/1000002
curl -G
-d 'access_token=<ACCESS_TOKEN>'
https://graph.facebook.com/v2.5/1000002/insights

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:

SH
https://www.facebook.com/ads/ads_insights/export_report?report_run_id=<REPORT_ID>&format=<REPORT_FORMAT>&access_token=<ACCESS_TOKEN>

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 accounting 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.

About Facebook Ads

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:

  1. Reach – potentially you can reach more than 1 billion active Facebook users.
  2. 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.
  3. Pay-per-click – advertisers pay only for ads that have been clicked by the user.

Facebook Ads Data Preparation for PostgreSQL

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 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 handle everything automatically for you.

RudderStack with one click integrates with sources or services, creates analytics-ready data, and syncs your Facebook Ads to PostgreSQL right away.

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.

Get Started Image

Get started today

Start building smarter customer data pipelines today with RudderStack. Our solutions engineering team is here to help.

Customer Data Platform for Developers | RudderStack
HIPPA Compliant
SOC 2 TYPE 2Users love RudderStack on G2