How to load data from Square to Redshift
How to Extract my data from Square?
As a platform, Square exposes several different APIs that cover different needs.
- E-commerce API, with which you can take payments using
- Register API, which can be used to build your own applications for in-store or mobile payments.
- Item & inventory management API.
- Sales reporting & Analytics API.
- Employee management API.
Square is currently maintaining two versions of the API, Connect v1 and Connect v2. There’s also an SDK for the Register API. It is possible that you might need to use both v1 and v2 of the Connect API, as not all endpoints have been implemented in the second and newest version. Mixing the two API versions together is encouraged by Square.
All the APIs that Square exposes are web APIs. As Web APIs follow the RESTful architecture principles, they 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 favourite language or framework. A few suggestions:
- Apache HttpClient for Java
- Spray-client for Scala
- Hyper for Rust
- Ruby rest-client
- Python http-client
Square also maintains official SDKs or libraries for the following languages:
Because of the popularity of Square, a number of unofficial libraries/SDKs are also implemented, so a quick search on Google or Github will help you find a library for your favourite framework or language.
Square API Authentication
In order to use the Square API, you first need to register a new application with Square. By doing that, you are also generating credentials that will be used to access the API endpoints.
To register your application:
- Go to https://connect.squareup.com/apps and sign in to your Square account.
- Click New Application and enter a name for your application.
- Click Create App.
The application dashboard displays your new app’s credentials. One of these credentials is the personal access token. This token gives your application full access to your own Square account. Copy its value to use in the next step.
Square API Rate Limiting
If Connect API endpoints receive too many requests associated with the same application or access token in a short time window, they might respond with a 429 Too Many Requests error. If this occurs, try your request again at a later time. The current rate is on the order of 10 QPS. This might change in the future and is not officially documented, so make sure that you properly handle our requests and responses.
Pull Data from the Square Platform
As mentioned earlier, Square exposes a number of APIs for different applications. Thus each one offers different opportunities for pulling useful data out of it. In this post, we will focus on how to get meaningful data out of the Square Connect API that can be used for analytics.
The Square Connect API allows us to use the Square platform to execute payment transactions, so a large number of endpoints are related to these tasks. We do not need to access these endpoints for analytic purposes. In a payment system, what we need to track and use as data for further analysis are events related to what is happening on our system. For example, we would like to be able to track when a new payment had happened, when something went wrong with a transaction, etc. To do that, we need to monitor the system for specific events and make sure that we store these events in a data warehouse solution like AWS Redshift for further analysis.
Square Connect API offers a notification through the webhooks mechanism to receive notifications any time an important event happens in our system. We can use this mechanism to track and record events from the Square Platform for analytics. We can receive real-time webhook notifications as a merchant accepts payments. Get started with webhooks with the following steps:
- Open your application’s settings from the application dashboard and select the Webhooks tab.
- Click Enable Webhooks if it isn’t already enabled.
- In the Notification URL field, specify the URL of your webhook page and click Save.
- Subscribe to webhook notifications from your own merchant account by sending the following curl request to the Update Webhooks endpoint (providing your personal access token and location ID where indicated):
SH
curl -X PUT -H "Authorization: Bearer PERSONAL_ACCESS_TOKEN" -H "Content-Type: application/json" -d "[\"PAYMENT_UPDATED\"]" https://connect.squareup.com/v1/LOCATION_ID/webhooks
By doing the above, we request the Square Connect API to notify us every time a new payment is happening, so we can track these events. The API is near real-time and you will receive the notification in no more than 60 seconds from the moment it happens.
The event that will be sent to our webhook will look like this:
JSON
{"merchant_id": "18YC4JBH91E1H","location_id": "JGHJ0343","event_type": "PAYMENT_UPDATED","entity_id": "Jq74mCczmFXk1tC10GB"}
As the above event does not include information that can be used directly, we will have to extract the “entity_id” value and use it to poll the “RetrieveTransaction” endpoint to get the full details of the event. If we do that, we will get a full response like the following:
JSON
{"transaction": {"id": "KnL67ZIwXCPtzOrqj0HrkxMF","location_id": "18YC4JDH91E1H","created_at": "2016-03-10T22:57:56Z","tenders": [{"id": "MtZRYYdDrYNQbOvV7nbuBvMF","location_id": "18YC4JDH91E1H","transaction_id": "KnL67ZIwXCPtzOrqj0HrkxMF","created_at": "2016-03-10T22:57:56Z","note": "some optional note","amount_money": {"amount": 5000,"currency": "USD"},"processing_fee_money": {"amount": 138,"currency": "USD"},"type": "CARD","card_details": {"status": "CAPTURED","card": {"card_brand": "VISA","last_4": "1111"},"entry_method": "KEYED"}}],"reference_id": "some optional reference id","product": "EXTERNAL_API"}}
This complete transaction object can be used for analysis purposes.
As we can see, getting data from the Square platform to do analytics requires the combination of both a pull and push logic where the platform first notifies us about events. Then we pull out the complete transaction object by performing requests to the API. This approach might make the whole process a bit complicated, especially if we consider that the above example covers just one event type. We would like to do that for every possible event that the platform tracks.
How can I prepare my Square 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 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 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 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 your data on one of the data sources that are supported as input by Redshift, these are the following:
How can I Load my data from Square to Redshift?
The first step to load your data from Square 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 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 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 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 you’ll be using a Kinesis Agent for pushing your data into the stream.
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.
SH
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:
SH
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.
What is the best way to load data from Square to Amazon Redshift and what are the 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 problem automatically for you.
RudderStack integrates with multiple sources or services like databases, CRM, email campaigns, analytics, and more. Don't want to go through the pain of direct integration? RudderStack’s Square to Redshift integration makes it easy to send data from Square to Redshift.