How to load data from SendGrid to Google BigQuery

Extract your data from SendGrid

There are two main methods to get our data from SendGrid, the first one is to pull data out from it and the second one is for SendGrid to push data to you whenever an important event is triggered, the second solution is also offering a real-time aspect to the analytics we can perform with SendGrid. We will see how we can access data from both.

In order to pull data from SendGrid, we need to access its HTTP API. As a Web API following the RESTful architecture principles, it can be accessed through HTTP. 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:

SendGrid maintains a number of officially supported clients or SDKs that you can use with your favorite language to access it without having to mess with the raw underlying HTTP calls. These are the following:

There’s also a huge list of community-supported libraries that you can use if you wish, a complete list can be found here.

SendGrid is currently maintaining 4 APIs that can be accessed.

  1. SMTP API. SendGrid’s SMTP API allows developers to specify custom handling instructions for e-mail.
  2. Web API v3. The latest version of the SendGrid API is completely RESTful, fully featured, and easy to integrate.
  3. Web API v2. The previous version of the SendGrid API still maintained for compatibility reasons. It is recommended that v3 is used instead of it as soon as possible.
  4. Webhooks. Webhooks are an easy way to get push notifications from SendGrid.

For this guide, we are considering the v3 of the Web API and Webhooks.

SendGrid API Authentication

Authentication for accessing the SendGrid Web API happens through API keys. You generate an API Key that then you can pass together with your requests to the API and your application will be authenticated. Additionally to the creation of API Keys, SendGrid also allows the creation and management of API Key permission lists. So you can create Keys that will have different levels of access to SendGrid for your account. API requests you make to the Web API v3 must be authenticated by including an Authorization Header with your API Key.

SendGrid Rate Limiting

There are limitations to delivery rates imposed by recipient mail servers. Exceeding these limitations results in a practice referred to as throttling. Throttling in terms of email means that a recipient mail server has accepted all the mail it is willing to accept from your IP for a certain period of time. Apart from throttling that can occur depending on the recipients’ server, SendGrid is also limiting the number of emails that you can send on a per month period, based on the plan that you have purchased, for more information about this you should consult the pricing page of SendGrid.

Endpoints and Available Resources

Some of the most important endpoints that SendGrid exposes are the following, you can also find the complete list of endpoints the Web API v3 exposes here:

  • Operations related to your users.
  • Marketing Campaigns. Campaign-related operations about loading in contacts, create segments, create and send campaigns, view your stats, and much more.
  • Operations related to white label lists of domains and subdomains, IPs and URLS.
  • SendGrid email statistics.
  • Spam reports. Operations, related to spam reports that SendGrid generates for your emails and campaigns.

And much more can be found on the link given above.

Not all of the provided endpoints are useful for pulling out data that can be used for analytics. the most important for this job is the Stats and reports endpoints that SendGrid exposes. As an example, let’s assume that we want to fetch data from the Global Stats endpoint. To do that we need to perform a GET request to the following URL, providing a valid API key:

SH
GET https://api.sendgrid.com/v3/stats?start_date=2015-01-01&end_date=2015-01-02 HTTP/1.1

If you pay attention to the above URL you will notice that we are also providing two parameters, the start and end dates for which we would like to fetch statistics for. The response will be in JSON format and will look like the following:

JSON
HTTP/1.1 200
[
{
"date": "2015-01-01",
"stats": [
{
"metrics": {
"blocks": 1,
"bounce_drops": 0,
"bounces": 0,
"clicks": 0,
"deferred": 1,
"delivered": 1,
"invalid_emails": 1,
"opens": 1,
"processed": 2,
"requests": 3,
"spam_report_drops": 0,
"spam_reports": 0,
"unique_clicks": 0,
"unique_opens": 1,
"unsubscribe_drops": 0,
"unsubscribes": 0
}
}
]
},
…………….
]

Statistics consist of the following metrics:

And there are a number of sub-endpoints that you can access for more specific metrics and statistics, these are the following:

  • Advanced Stats
  • Category Stats
  • Global Stats
  • Parse Stats
  • Subuser Stats

Another way of retrieving metrics and statistics from the SendGrid API is by requesting it to push data to our system every time a new event occurs. To do that we need to use the Webhooks API which sends events to a predefined URL using POST requests. Events that are sent by the SendGrid API have a structure like the following:

JSON
[
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe@sendgrid.com",
"timestamp": 1337197600,
"smtp-id": "<4FB4041F.6080505@sendgrid.com>",
"event": "processed"
},
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe@sendgrid.com",
"timestamp": 1337966815,
"category": "newuser",
"event": "click",
"url": "https://sendgrid.com"
},
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe@sendgrid.com",
"timestamp": 1337969592,
"smtp-id": "<20120525181309.C1A9B40405B3@Example-Mac.local>",
"event": "group_unsubscribe",
"asm_group_id": 42
}
]

These events can be stored in your BI solution like Google BigQuery for analysis or they can be used to trigger specific actions as they arrive.

Prepare data from SendGrid to Google BigQuery

Before you load your data into BigQuery, you should make sure that it is presented in a format supported by it, so for example if the API you pull data from returns XML you have to first transform it into a serialization that BigQuery understands. Currently, two data formats are supported:

You also need to make sure that the data types you are using are the ones supported by BigQuery, which are the following:

  • STRING
  • INTEGER
  • FLOAT
  • BOOLEAN
  • RECORD
  • TIMESTAMP

for more information please check the Preparing Data for BigQuery page on the documentation.

Load Data from SendGrid to Google BigQuery

If you want to load data from SendGrid to BigQuery, you have to use one of the following supported data sources.

  1. Google Cloud Storage
  2. Sent data directly to BigQuery with a POST request
  3. Google Cloud Datastore Backup
  4. Streaming insert
  5. App Engine log files
  6. Cloud Storage logs

From the above list of sources, 5 and 6 are not applicable in our case.

For Google Cloud Storage, you first have to load your data into it, there are a few options on how to do this, for example, you can use the console directly as it is described here and do not forget to follow the best practices. Another option is to post your data through the JSON API, as we see again APIs play an important role in both the extraction but also the loading of data into our data warehouse.. In its simplest case, it’s just a matter of one HTTP POST request using a tool like CURL or Postman. It should look like the following example.

MARKDOWN
POST /upload/storage/v1/b/myBucket/o?uploadType=media&name=myObject HTTP/1.1
Host: www.googleapis.com
Content-Type: application/text
Content-Length: number_of_bytes_in_file
Authorization: Bearer your_auth_token
your SendGrid data

and if everything went ok, you should get something like the following as a response from the server:

MARKDOWN
HTTP/1.1 200
Content-Type: application/json
{
"name": "myObject"
}

Working with Curl or Postman, is good only for testing, if you would like to automate the process of loading your data into Google Bigquery, you should write some code to send your data to Google Cloud Storage. In case you are developing on the Google App Engine you can use the library that is available for the languages that are supported by it:

If you are using one of the above languages and you are not coding for the Google App Engine, you can use it to access the Cloud Storage from your environment. Interacting such a feature-rich product like Google Cloud Storage can become quite complicated depending on your use case, for more details on the different options that exist you can check Google Cloud Storage documentation. If you are looking for a less engaged and more neutral way of using Cloud Storage, you can consider a solution like RudderStack.

After you have loaded your data into Google Cloud Storage, you have to create a Load Job for BigQuery to actually load the data into it, this Job should point to the source data in Cloud Storage that have to be imported, this happens by providing source URIs that point to the appropriate objects.

The previous method described, used a POST request to the Google Cloud Storage API for storing the data there and then load it into BigQuery. Another way to go is to do a direct HTTP POST request to BigQuery with the data you would like to query. This approach is similar to how we loaded the data to Google Cloud Storage through the JSON API, but it uses the appropriate end-points of BigQuery to load the data there directly. The way to interact with it is quite similar, for more information can be found on the Google BigQuery API Reference and on the page that describes how to load data into BigQuery using POST. You can interact with it using the HTTP client library of the language or framework of your choice, a few options are:

The best way of loading data from SendGrid to Google BigQuery

So far we just scraped the surface of what you can do with BigQuery and how you can 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 SendGrid to BigQuery 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.
Don't want to go through the pain of direct integration? RudderStack's Twilio SendGrid integration makes it easy to send data from Twilio SendGrid to Google BigQuery.