How to Load data from SendGrid to SQL Data Warehouse

What is SendGrid?

Sendgrid‘s mission is to help you to deliver your transactional and marketing email through one reliable platform. It is a transactional email platform offering services similar to Mandrill and mailgun. Although there’s a belief that SendGrid is more for newsletter-like email services, it can also be used for onboarding, registration, and any kind of personalized and targeted one-to-one emails to your customers. Some of the benefits that SendGrid offers are,

You can select which protocol to use for sending your emails. It can be either SMTP or HTTP, so it offers flexibility on the protocol level.

Scalable SendGrid offers an infrastructure capable of scaling up and down just as your mailing needs do. No matter if you send 100 or a billion emails, SendGrid can handle the load transparently for you.

Guaranteed mail delivery. Compliance with CAN-SPAM and management of spamming and reputation for mail servers can guarantee a much higher delivery rate for your emails. You can be sure that your emails will not be mistaken for spam from the recipient mail server.

Easy and fast integration. No matter what kind of emails you want to send, transactional or marketing, custom integration with SendGrid is extremely easy. Different APIs exist to cover different needs together with a large number of SDKs and libraries that can ease even further the integration process. You can have SendGrid integrated, up and running in a matter of minutes.

Security. All emails sent via SendGrid utilize opportunistic TLS encryption, so as long as your recipient servers are configured to use TLS you can be sure that all emails will be sent via a secure channel to them.

Powerful and Actionable Analytics. Everything related to your marketing campaigns or transactional emails that can be tracked is reported by the SendGrid platform in real-time. Analytics can be either used through the dashboards that SendGrid has or can be pulled by the API to be used as part of custom analytics solutions, which is also the scope of this article.

Just like every platform that offers programmatic access to email, SendGrid has been built from the ground up as an API company. This means that in order to gain full access to its capabilities you will need to incorporate some technical skills. Nevertheless, SendGrid also offers an intuitive web environment that can be used by marketers to manage and execute marketing campaigns without the need for technical support.

How to Extract my 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 email.
  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. The operations related to spam reports that SendGrid generates for your emails and campaigns.

And much more can be found here.

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:

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 SQL Data Warehouse for analysis or they can be used to trigger specific actions as they arrive.

How can I Load my data from SendGrid to SQL Data Warehouse?

SQL Data Warehouse supports numerous options for loading data, such as:

  • PolyBase
  • Azure Data Factory
  • BCP command-line utility
  • SQL Server integration services

As we are interested in loading data from online services by using their exposed HTTP APIs, we will not consider the usage of BCP command-line utility or SQL server integration in this guide. We’ll consider the case of loading our data as Azure storage Blobs and then use PolyBase to load the data into SQL Data Warehouse.

Accessing these services happens through HTTP APIs. As we see again, APIs play an important role in both the extraction and the loading of data into our data warehouse. You can access these APIs by using a tool like CURL or Postman. Or use the libraries provided by Microsoft for your favorite language. Before you actually upload any data, you have to create a container similar to a concept to the Amazon AWS Bucket. Creating a container is a straightforward operation, and you can do it by following the instructions found on the Blob storage documentation from Microsoft. As an example, the following code can create a container in Node.js.

JAVASCRIPT
blobSvc.createContainerIfNotExists('mycontainer', function(error, result, response){
if(!error){
// Container exists and allows
// anonymous read access to blob
// content and metadata within this container
}
});

After the creation of the container you can start uploading data to it by using again the given SDK of your choice in a similar fashion:

JAVASCRIPT
blobSvc.createBlockBlobFromLocalFile('mycontainer', 'myblob', 'test.txt', function(error, result, response){
if(!error){
// file uploaded
}
});

When you are done putting your data into Azure Blobs, you are ready to load it into SQL Data Warehouse using PolyBase. To do that, you should follow the directions in the Load with PolyBase documentation. In summary, the required steps to do it are the following:

  • create a database master key
  • create a database scoped credentials
  • create an external file format
  • create an external data source

PolyBase’s ability to transparently parallelize loads from Azure Blob Storage will make it the fastest tool for loading data. After configuring PolyBase, you can load data directly into your SQL Data Warehouse by simply creating an external table that points to your data in storage and then mapping that data to a new table within SQL Data Warehouse.

Of course, you will need to establish a recurrent process that will extract any newly created data from your service, load them in the form of Azure Blobs and initiate the PolyBase process for importing the data again into SQL Data Warehouse. One way of doing this is by using the Azure Data Factory service. If you would like to follow this path, you can read some good documentation on how to move data to and from Azure SQL Warehouse using Azure Data Factory.

What is the best way to load data from SendGrid to SQL Data Warehouse? Which are the possible alternatives?

So far we just scraped the surface of what can be done with Microsoft Azure SQL Data Warehouse and how to load data into it. The way to proceed relies heavily on the data you want to load, from which service they are coming from, and the requirements of your use case. Things can get even more complicated if you want to integrate data coming from different sources. A possible alternative, instead of writing, hosting, and maintaining a flexible data infrastructure, is to use a product like RudderStack that can handle this kind of problem automatically for you.

RudderStack with multiple sources or services like databases, CRM, email campaigns, analytics and more.

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.