How to load data from SendGrid to Redshift
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 and 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 using tools like CURL or Postman or 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
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:
- SMTP API - SendGrid’s SMTP API allows developers to specify custom handling instructions for e-mail.
- Web API v3 -The latest version of the SendGrid API, which is completely RESTful, fully-featured, and easy to integrate.
- 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.
- 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 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.
Not all of the provided endpoints are useful for pulling out data that can be used for analytics. the most important for this job are 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:
JAVASCRIPT
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:
JAVASCRIPT
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:
- Blocks
- Bounces
- Bounce Drops
- Clicks
- Delivered
- Deferrals
- Drops
- Invalid Emails
- Processed
- Received
- Requests
- Spam Reports
- Unique Clicks
- Unique Opens
- Spam Report Drops
- Unsubscribe Drops
- Unsubscribes
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 to 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:
JAVASCRIPT
[{"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 Amazon Redshift for analysis or they can be used to trigger specific actions as they arrive.
Prepare your SendGrid Data for Amazon Redshift
Amazon Redshift is built around industry-standard SQL with added functionality to manage very large datasets and high performance analysis. So, in order to load your data into it you will have to follow its data model which is a typical relational database model. The data you extract from your data source should be mapped into tables and columns. Where you can consider the table as a map to the resource you want to store and columns the attributes of that resource. Also, each attribute should adhere to the datatypes that are supported by Redshift, currently the datatypes that are supported are the following:
- SMALLINT
- INTEGER
- BIGINT
- DECIMAL
- REAL
- DOUBLE PRECISION
- BOOLEAN
- CHAR
- VARCHAR
- DATE
- TIMESTAMP
As your data are probably coming in a representation like JSON that supports a much smaller range of data types you have to be really careful about what data you feed into Redshift and make sure that you have mapped your types into one of the datatypes that is supported by Redshift. Designing a Schema for Redshift and mapping the data from your data source to it is a process that you should take seriously as it can both affect the performance of your cluster and the questions you can answer. It’s always a good idea to have in your mind the best practices that Amazon has published regarding the design of a Redshift database. When you have concluded on the design of your database, you need to load your data on one of the datasources that are supported as input by Redshift, these are the following:
Load data from SendGrid to Redshift
The first step to load your data from SendGrid to Redshift is to put them in a source that Redshift can pull it from. As it was mentioned earlier there are three main data sources supported, Amazon S3, Amazon DynamoDB and Amazon Kinesis Firehose, with Firehose being the most recent addition as a way to insert data into Redshift.
To upload your data to Amazon S3 you will have to use the AWS REST API, as we see again APIs play an important role in both the extraction and the loading of data into our data warehouse. The first task that you have to perform is to create a bucket, you do that by executing an HTTP PUT on the Amazon AWS REST API endpoints for S3. You can do this by using a tool like CURL or Postman. Or use the libraries provided by Amazon for your favourite language. You can find more information by reading the API reference for the Bucket operations on Amazon AWS documentation.
After you have created your bucket you can start sending your data to Amazon S3, using again the same AWS REST API but by using the endpoints for Object operations. As in the Bucket case you can either access the HTTP endpoints directly or use the library of your preference.
DynamoDB imports data again from S3, it adds another step between S3 and Amazon Redshift so if you don’t need it for other reasons you can avoid it.
Amazon Kinesis Firehose is the latest addition as a way to insert data into Redshift and offers a real-time streaming approach into data importing. The necessary steps for adding data to Redshift through Kinesis Firehose are the following:
- create a delivery stream
- add data to the stream
Whenever you add new data to the stream, Kinesis takes care of adding these data to S3 or Redshift, again going through S3 in this case is redundant if your goal is to move your data to Redshift. The execution of the previous two steps can be performed either through the REST API or through your favourite library just as in the previous two cases. The difference here is that for pushing your data into the stream you’ll be using a Kinesis Agent.
Amazon Redshift supports two methods for loading data into it. The first one is by invoking an INSERT command. You can connect to your Amazon Redshift instance with your client, using either a JDBC or ODBC connection and then you perform an INSERT command for your data.
JAVASCRIPT
insert into category_stage values(12, 'Concerts', 'Comedy', 'All stand-up comedy performances');
The way you invoke the INSERT command is the same as you would do with any other SQL database, for more information you can check the INSERT examples page on the Amazon Redshift documentation.
Redshift is not designed for INSERT-like operations. On the contrary, the most efficient way of loading data into it is by doing bulk uploads using a COPY command. You can perform a COPY command for data that lives as flat files on S3 or from an Amazon DynamoDB table. When you perform COPY commands, Redshift can read multiple files simultaneously, automatically distribute the workload to the cluster nodes, and perform the load in parallel. As a command, COPY is quite flexible and allows for many different ways of using it, depending on your use case. Performing a COPY on amazon S3 is as simple as the following command:
JAVASCRIPT
copy listingfrom 's3://mybucket/data/listing/'credentials 'aws_access_key_id=;aws_secret_access_key=';
For more examples on how to invoke a COPY command, you can check the COPY examples page on Amazon Redshift documentation. As in the INSERT case, the way to perform the COPY command is by connecting to your Amazon Redshift instance using a JDBC or ODBC connection and then invoke the commands you want using the SQL Reference from Amazon Redshift documentation.
The best way of loading data from SendGrid to Amazon Redshift
So far we just scraped the surface of what you can do with Amazon Redshift and how you can load data into it. Things can get even more complicated if you want to integrate data coming from different sources.
Instead of writing, hosting, and maintaining a flexible data infrastructure, RudderStack can handle everything automatically for you.
RudderStack, with one click, integrates with sources or services, creates analytics-ready data, and syncs your SendGrid to Redshift right away.