How to load data from Stripe to Redshift
Extract your data from Stripe
Stripe is an API first product, it’s a unified set of APIs and tools that instantly enables businesses to accept and manage online payments. It is a web API following the RESTful principles, they try to use as many as possible HTTP built-in features to make it accessible to off-the-shelf HTTP clients and the serialization they support for their responses is JSON.
They also have two different types of keys used for authentication, one for testing mode and one for live mode, using the testing mode key it becomes easy to test every aspect of the API without messing with your real data. Also, keep in mind that the calls you make to the Stripe API have to be over HTTPS only for security reasons, plain HTTP calls will fail, same happens for non-authenticated calls, so do not forget to use your testing mode key in case you want to experiment with the API.
Currently, the Stripe API is built around the following ten core resources:
- Balance – an object that represents your stripe balance.
- Charges – to charge a credit or debit card you create a charge
- Customers – Customer objects allow you to perform recurring charges and track multiple charges that are associated with the same customer.
- Dispute – A dispute occurs when a customer questions your charge with their bank or credit card company.
- Events – Events are our way of letting you know when something interesting happens in your account.
- File uploads – There are various times when you’ll want to upload files to Stripe (for example, when uploading dispute evidence).
- Refunds – Refund objects allow you to refund a charge that has previously been created but not yet refunded.
- Tokens – Tokens can be created with your publishable API key.
- Transfers – When Stripe sends you money or you initiate a transfer to a bank account
- Transfer reversals – A previously created transfer can be reversed if it has not yet been paid out.
All of the above resources support CRUD operations by using HTTP verbs on their associated endpoints. As a web API, you can access it by using tools like CURL or Postman or your favorite HTTP client for the language or framework of your choice. Some options are the following:
- Apache HttpClient for Java
- Spray-client for Scala
- Hyper for Rust
- Ruby rest-client
- Python http-client
There’s also a large number of libraries that wrap around the Stripe API and offer an easier way to interact with it, both community developed and from Stripe. For more information, you can check the libraries section in the API documentation.
Stripe and any other service that you might be using, has figured out (hopefully) the optimal model for its operations, but when we fetch data from them we usually want to answer questions or do things that are not part of the context that these services operate, something that makes these models suboptimal for your analytic needs.
For this reason, we should always keep in mind that when we work with data coming from external services we need to remodel it and bring it to the right form for our needs.
Let’s assume that we want to perform some churn analysis for our company and to do that we need customer data that indicate when they have canceled their subscriptions. To do that we’ll have to request the customer objects that Stripe holds for our company. We can do that with the following command:
JAVASCRIPT
curl https://api.stripe.com/v1/charges?limit=3-u sk_test_BQokikJOvBiI2HlWgH4olfQ2:
A typical response will look like the following:
JAVASCRIPT
{"object": "list","url": "/v1/charges","has_more": false,"data": [{"id": "ch_17SY5f2eZvKYlo2CiPfbfz4a","object": "charge","amount": 500,"amount_refunded": 0,"application_fee": null,"balance_transaction": "txn_17KGyT2eZvKYlo2CoIQ1KPB1","captured": true,"created": 1452627963,"currency": "usd","customer": null,"description": "thedude@grepinnovation.com Account Credit","destination": null,"dispute": null,"failure_code": null,"failure_message": null,"fraud_details": {},
Inside the customer object there’s a list of subscription objects that look like the following JSON document:
JAVASCRIPT
{"id": "sub_7hy2fgATDfYnJS","object": "subscription","application_fee_percent": xxxx,"cancel_at_period_end": false,"canceled_at": xxxx,"current_period_end": 1455306419,"current_period_start": 1452628019,"customer": "cus_7hy0yQ55razJrh","discount": xxxx,"ended_at": xxxx,"metadata": {},"plan": {"id": "gold2132","object": "plan","amount": 2000,"created": 1386249594,"currency": "usd","interval": "month","interval_count": 1,"livemode": false,"metadata": {},"name": "Gold ","statement_descriptor": null,"trial_period_days": null},"quantity": 1,"start": 1452628019,"status": "active","tax_percent": null,"trial_end": null,"trial_start": null}
These objects together with part of the customer object, contain the information we need to perform churn analysis. Of course, we’ll have to extract all the information we need, map it to the schema of our data warehouse repository and then load the data to it following the instructions of this post.
Stream data from the Stripe API to a data warehouse
It is also possible to set up a streaming data infrastructure that will collect Stripe data and push them into your data warehouse in a streaming fashion. This can be achieved by using the webhooks functionality that Stripe supports, you register some events to it and every time something happens, Stripe will push a message to your webhook.
For more information about that, check the API documentation on webhooks.
Prepare your Stripe 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 data into it, you will have to follow its data model which is a typical relational database model. The data you extract from a 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 data types that are supported by Redshift, currently the data types that are supported are the following:
- SMALLINT
- INTEGER
- BIGINT
- DECIMAL
- REAL
- DOUBLE PRECISION
- BOOLEAN
- CHAR
- VARCHAR
- DATE
- TIMESTAMP
As the 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 data types that is supported by Redshift.
Designing a Schema for Redshift and mapping the data from a 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 that 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 the data on one of the data sources that are supported as input by Redshift, these are the following:
Load data from Stripe to Redshift
The first step to load your Stripe data 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 any 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 but also 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 favorite 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 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 favorite library just as in the previous two cases. The difference here is that for pushing 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.
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 is able to read multiple files in simultaneously and it automatically distributes the workload to the cluster nodes and performs 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 to load data from Stripe to Redshift and possible alternatives
So far we just scraped the surface of what can be done with Amazon Redshift 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 problems automatically for you.
RudderStack integrates with multiple sources or services like databases, CRM, email campaigns, analytics, and more. Quickly and safely move all your data from Stripe to Redshift and start generating insights.