How to Load data from SendGrid to MS SQL Server
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 of 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:
- 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 is completely RESTful, fully featured, and easy to integrate.
- Web API v2. The previous version of the SendGridAPI, 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 creating 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.
About 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 a newsletter-like email service, it can also be used for on-boarding, 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 e-mails. 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 e-mails, 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 e-mails. You can be sure that your e-mails will not be mistaken with spam from the recipient mail server.
- Easy and fast integration. No matter what kind of e-mails 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 send via SendGrid utilize opportunistic TLS encryption, so as long as your recipient servers are configured to use TLS, you can be sure that all mails 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.
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 v3exposes 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 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. 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, and 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:
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 data warehouse solution like MS SQL Server for analysis or they can be used to trigger specific actions as they arrive.
About Microsoft SQL Server
Microsoft SQL Server is one of the oldest and most mature database systems. Its first version was introduced about 28 years ago, in 1989, and Microsoft has been consistently supporting and extending the product until today.
So, it’s no surprise that Microsoft SQL Server has one of the richest feature sets among the currently available database systems.
SQL Server is delivered in different editions or flavors. The most notable being the Enterprise edition which can manage databases as large as 524 petabytes utilizing up to 12 terabytes of memory and 640 CPU processors. A free and scaled-down version is called Express.
A Business Intelligence version is focusing on use cases where BI is performed on-premises. This version is actually a bundle of different products, including the core database system, together with other Microsoft-related products that can be used for BI purposes like visualization and data management.
In addition, there are also plenty of specialized versions of the database like the Compact edition that can be used on small devices and of course, the Azure version, which is the cloud-based edition of SQL Server. Microsoft SQL Server incorporates a modular architecture that can extend the database with additional services. Replication services can extend the database to a cluster version and thus help with scaling and fault tolerance.
The SQL Server Analysis Services augment the database with OLAP and data mining capabilities, making the database ideal for the workloads that we care about in this guide.
SendGrid Data Preparation for Microsoft SQL Server
As in every relational database, SQL Server requires a well-defined database schema before we start populating with data. Data is organized in schemas, which are distinct namespaces where database objects belong to.
The most common database objects are of course tables that have a number of columns, with each one having a declared data type. MS SQL Server supports a large number of different data types. This gives us great flexibility in expressing the data that we have and at the same time optimizing our data warehouse.
When working with data coming from web services, where data is usually serialized in JSON, it is important to correctly map the data to the right data types. As changing the data types in the future is a process that might cost in downtime of your database, it is important to spend enough time thinking about the proper data type assignments.
For example, dates in JSON are just strings, but when storing date objects in a database, we can enhance analytics with great capabilities by transforming the raw string data into an appropriate date type. A typical strategy for loading data from SendGrid to an SQL Server database is to create a schema where you will map each API endpoint to a table. Each key inside the SendGridAPI endpoint response should be mapped to a column of that table and you should ensure the right conversion to an SQL Server compatible data type.
Of course, you will need to ensure that as the data types from the SendGridAPI might change, you will adapt your database tables accordingly. There’s no such thing as automatic data type casting. After you have a complete and well-defined data model or schema for Microsoft SQL Server, you can move forward and start loading your data into the database.
Load data from SendGrid to MS SQL Server
As a feature-rich and mature product, MS SQL Server offers a large and diverse set of methods for loading data into a database. One way of importing data into your database is by using the SQL Server Import and Export Wizard. With it and through a visual interface you will be able to bulk load data from a number of data sources that are supported.
You can import data from another SQL Server, from an Oracle database, from Flat Files, from an Access Data Source, PostgreSQL, MySQL, and finally Azure Blob Storage. Especially if you are using a managed version of MS SQL Server on Azure, you should definitely consider utilizing the Azure Blob Storage connection.
In this way, you will be loading data as Blobs on Azure, and your MS SQL Server database will sync with it through the Import and Export Wizard.
Another way for importing bulk data into an SQL Server, both on Azure and on premises, is by using the bcp utility. This is a command line tool that is built specifically for bulk loading and unloading of data from an MS SQL database.
Finally and for compatibility reasons, especially if you are managing databases from different vendors, you can you BULK INSERT SQL statements.
In a similar way and as it happens with the rest of the databases, you can also use the standard INSERT statements, where 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.
So for bulk datasets, you better consider one of the previous methods.
Updating your SendGrid data on MS SQL Server
As you will be generating more data on SendGrid, you will need to update your older data on an MS SQL Server database. This includes new records together with updates to older records that, for any reason, have been updated on SendGrid.
You will need to periodically check SendGrid 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 SQL Server table is achieved by creating UPDATE statements.
Another issue that you need to take care of is identifying and removing any duplicate records on your database. Either because SendGrid 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 MS SQL Server features like TRANSACTIONS can help tremendously, although they do not solve the problem in the general case.
The best way of loading data from SendGrid to MS SQL Server
So far, we just scraped the surface of what you can do with MS SQL Server 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 MS SQL Server right away.
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 MS SQL Server.