How to Build an ETL App for Amazon Athena Data in Python with CData Connect AI

Jerod Johnson
Jerod Johnson
Director, Technology Evangelism
Build ETL pipelines that read and write live Amazon Athena data in Python with petl and the CData Connect AI Python SDK.

The rich ecosystem of Python modules lets you get to work quickly and integrate your systems more effectively. With the CData Connect AI Python SDK and the petl framework, you can build Amazon Athena-connected applications and pipelines for extracting, transforming, and loading Amazon Athena data. This article shows how to connect to Connect AI and use petl to extract, transform, and load Amazon Athena data.

The Connect AI Python SDK (cdata-connect-ai) is a DB-API 2.0 (PEP 249) compliant client, so petl can read directly from the SDK connection with etl.fromdb. There is no driver to install per source: connect with a Personal Access Token and build your pipeline.

About Amazon Athena Data Integration

CData provides the easiest way to access and integrate live data from Amazon Athena. Customers use CData connectivity to:

  • Authenticate securely using a variety of methods, including IAM credentials, access keys, and Instance Profiles, catering to diverse security needs and simplifying the authentication process.
  • Streamline their setup and quickly resolve issue with detailed error messaging.
  • Enhance performance and minimize strain on client resources with server-side query execution.

Users frequently integrate Athena with analytics tools like Tableau, Power BI, and Excel for in-depth analytics from their preferred tools.

To learn more about unique Amazon Athena use cases with CData, check out our blog post: https://www.cdata.com/blog/amazon-athena-use-cases.


Getting Started


Connect to Amazon Athena in Connect AI

CData Connect AI uses a straightforward, point-and-click interface to connect to data sources.

  1. Log into Connect AI, click Sources, and then click Add Connection
  2. Adding a Connection
  3. Select "Amazon Athena" from the Add Connection panel
  4. Selecting a data source
  5. Enter the necessary authentication properties to connect to Amazon Athena.

    Authenticating to Amazon Athena

    To authorize Amazon Athena requests, provide the credentials for an administrator account or for an IAM user with custom permissions: Set AccessKey to the access key Id. Set SecretKey to the secret access key.

    Note: Though you can connect as the AWS account administrator, it is recommended to use IAM user credentials to access AWS services.

    Obtaining the Access Key

    To obtain the credentials for an IAM user, follow the steps below:

    1. Sign into the IAM console.
    2. In the navigation pane, select Users.
    3. To create or manage the access keys for a user, select the user and then select the Security Credentials tab.

    To obtain the credentials for your AWS root account, follow the steps below:

    1. Sign into the AWS Management console with the credentials for your root account.
    2. Select your account name or number and select My Security Credentials in the menu that is displayed.
    3. Click Continue to Security Credentials and expand the Access Keys section to manage or create root account access keys.

    Authenticating from an EC2 Instance

    If you are using the CData Data Provider for Amazon Athena 2018 from an EC2 Instance and have an IAM Role assigned to the instance, you can use the IAM Role to authenticate. To do so, set UseEC2Roles to true and leave AccessKey and SecretKey empty. The CData Data Provider for Amazon Athena 2018 will automatically obtain your IAM Role credentials and authenticate with them.

    Authenticating as an AWS Role

    In many situations it may be preferable to use an IAM role for authentication instead of the direct security credentials of an AWS root user. An AWS role may be used instead by specifying the RoleARN. This will cause the CData Data Provider for Amazon Athena 2018 to attempt to retrieve credentials for the specified role. If you are connecting to AWS (instead of already being connected such as on an EC2 instance), you must additionally specify the AccessKey and SecretKey of an IAM user to assume the role for. Roles may not be used when specifying the AccessKey and SecretKey of an AWS root user.

    Authenticating with MFA

    For users and roles that require Multi-factor Authentication, specify the MFASerialNumber and MFAToken connection properties. This will cause the CData Data Provider for Amazon Athena 2018 to submit the MFA credentials in a request to retrieve temporary authentication credentials. Note that the duration of the temporary credentials may be controlled via the TemporaryTokenDuration (default 3600 seconds).

    Connecting to Amazon Athena

    In addition to the AccessKey and SecretKey properties, specify Database, S3StagingDirectory and Region. Set Region to the region where your Amazon Athena data is hosted. Set S3StagingDirectory to a folder in S3 where you would like to store the results of queries.

    If Database is not set in the connection, the data provider connects to the default database set in Amazon Athena.

    Configuring a connection (Salesforce is shown)
  6. Click Save & Test
  7. Navigate to the Permissions tab and update the user-based permissions. Updating permissions

Generate a Personal Access Token (PAT)

The Python SDK authenticates to Connect AI with your account email and a Personal Access Token (PAT). It is best practice to create a separate PAT for each application to maintain granularity of access.

  1. Click the Gear icon () at the top right of the Connect AI app to open the Settings page.
  2. On the Settings page, go to the Access Tokens section and click Create PAT.
  3. Give the PAT a name and click Create. Creating a new PAT
  4. The PAT is only visible at creation, so copy it and store it securely.

Install Required Modules

Install the SDK and the petl framework using the pip utility:

pip install cdata-connect-ai
pip install petl

Build an ETL App for Amazon Athena Data in Python

Once the required modules are installed, you are ready to build the ETL app. Code snippets follow, but the full source code is available at the end of the article.

First, import the modules and connect to Connect AI with your account email and PAT:

import petl as etl
import cdata_connect_ai

conn = cdata_connect_ai.connect(
    username="[email protected]",
    password="<your_pat>",
)

Create a SQL Statement to Query Amazon Athena

Use SQL to create a statement for querying Amazon Athena. In this article, we read data from the Customers entity. Identifiers are three-part: <Connection>.<Schema>.<Table>, where the connection name defaults to the source name (for example, AmazonAthena1).

sql = (
    "SELECT Name, TotalDue "
    "FROM [AmazonAthena1].[AmazonAthena].[Customers] "
    "WHERE CustomerId = '12345'"
)

Extract, Transform, and Load the Amazon Athena Data

With a connection and query in hand, use petl to extract, transform, and load the Amazon Athena data. In this example, we extract Amazon Athena data, sort the data by the TotalDue column, and load the data into a CSV file.

table1 = etl.fromdb(conn, sql)

table2 = etl.sort(table1, 'TotalDue')

etl.tocsv(table2, 'customers_data.csv')

Load New Rows Back into Amazon Athena

When Amazon Athena supports writes, load rows back with a batch INSERT. The SDK's executemany takes @name placeholders and a list of parameter dictionaries, one per row.

cur = conn.cursor()
cur.executemany(
    "INSERT INTO [AmazonAthena1].[AmazonAthena].[Customers] (Name, TotalDue) "
    "VALUES (@val1, @val2)",
    [
        {"@val1": "New value 1", "@val2": "New value 1"},
        {"@val1": "New value 2", "@val2": "New value 2"},
    ],
)
print(f"Rows inserted: {cur.rowcount}")

conn.close()

Note: Even for writable sources, a read-only PAT or connection permission will reject write operations.

With the CData Connect AI Python SDK, you can work with Amazon Athena data just like you would with any database, including direct access to data in ETL packages like petl.

More Information and Free Trial

Now you can pipe live Amazon Athena data through petl using the CData Connect AI Python SDK. For more information on connecting to Amazon Athena (and hundreds of other data sources), visit the Connect AI page. Sign up for a free trial and start building data pipelines for live Amazon Athena data in Python.



Full Source Code

import petl as etl
import cdata_connect_ai

conn = cdata_connect_ai.connect(
    username="[email protected]",
    password="<your_pat>",
)

sql = (
    "SELECT Name, TotalDue "
    "FROM [AmazonAthena1].[AmazonAthena].[Customers] "
    "WHERE CustomerId = '12345'"
)

table1 = etl.fromdb(conn, sql)

table2 = etl.sort(table1, 'TotalDue')

etl.tocsv(table2, 'customers_data.csv')

cur = conn.cursor()
cur.executemany(
    "INSERT INTO [AmazonAthena1].[AmazonAthena].[Customers] (Name, TotalDue) "
    "VALUES (@val1, @val2)",
    [
        {"@val1": "New value 1", "@val2": "New value 1"},
        {"@val1": "New value 2", "@val2": "New value 2"},
    ],
)
print(f"Rows inserted: {cur.rowcount}")
conn.close()

Ready to get started?

Learn more about CData Connect AI or sign up for free trial access:

Free Trial