Skip to main content

Loading Klarna Data to CockroachDB with dlt in Python

tip

We will be using the dlt PostgreSQL destination to connect to CockroachDB. You can get the connection string for your CockroachDB database as described in the CockroachDB Docs.

Need help deploying these pipelines, or figuring out how to run them in your data stack?

Join our Slack community or book a call with our support engineer Violetta.

Loading data from Klarna to CockroachDB using the dlt library is a straightforward process designed to enhance your data management capabilities. Klarna is a global payment solutions provider known for its seamless online payment services, including 'buy now, pay later' options, installment plans, and direct payments. By integrating Klarna with CockroachDB, a distributed, cloud-native SQL database, you can leverage flexible payment solutions to improve customer satisfaction and boost conversion rates. The open-source dlt library simplifies this integration, ensuring reliable and efficient data transfer. For more information on Klarna, visit their website.

dlt Key Features

  • Scalability via iterators, chunking, and parallelization: dlt offers scalable data extraction by leveraging iterators, chunking, and parallelization techniques. This approach allows for efficient processing of large datasets by breaking them down into manageable chunks. Learn more
  • Implicit extraction DAGs: dlt incorporates the concept of implicit extraction DAGs to handle the dependencies between data sources and their transformations automatically. This ensures data consistency and integrity during the extraction process. Learn more
  • Automated maintenance: With schema inference and evolution and alerts, and with short declarative code, maintenance becomes simple. Learn more
  • Run it where Python runs: dlt can be run on Airflow, serverless functions, notebooks, and more. It requires no external APIs, backends, or containers, and scales on both micro and large infrastructure. Learn more
  • User-friendly, declarative interface: dlt's interface removes knowledge obstacles for beginners while empowering senior professionals. Learn more

Getting started with your pipeline locally

OpenAPI Source Generator dlt-init-openapi

This walkthrough makes use of the dlt-init-openapi generator cli tool. You can read more about it here. The code generated by this tool uses the dlt rest_api verified source, docs for this are here.

0. Prerequisites

dlt and dlt-init-openapi requires Python 3.9 or higher. Additionally, you need to have the pip package manager installed, and we recommend using a virtual environment to manage your dependencies. You can learn more about preparing your computer for dlt in our installation reference.

1. Install dlt and dlt-init-openapi

First you need to install the dlt-init-openapi cli tool.

pip install dlt-init-openapi

The dlt-init-openapi cli is a powerful generator which you can use to turn any OpenAPI spec into a dlt source to ingest data from that api. The quality of the generator source is dependent on how well the API is designed and how accurate the OpenAPI spec you are using is. You may need to make tweaks to the generated code, you can learn more about this here.

# generate pipeline
# NOTE: add_limit adds a global limit, you can remove this later
# NOTE: you will need to select which endpoints to render, you
# can just hit Enter and all will be rendered.
dlt-init-openapi klarna --url https://raw.githubusercontent.com/dlt-hub/openapi-specs/main/open_api_specs/Business/klarna.yaml --global-limit 2
cd klarna_pipeline
# install generated requirements
pip install -r requirements.txt

The last command will install the required dependencies for your pipeline. The dependencies are listed in the requirements.txt:

dlt>=0.4.12

You now have the following folder structure in your project:

klarna_pipeline/
├── .dlt/
│ ├── config.toml # configs for your pipeline
│ └── secrets.toml # secrets for your pipeline
├── rest_api/ # The rest api verified source
│ └── ...
├── klarna/
│ └── __init__.py # TODO: possibly tweak this file
├── klarna_pipeline.py # your main pipeline script
├── requirements.txt # dependencies for your pipeline
└── .gitignore # ignore files for git (not required)

1.1. Tweak klarna/__init__.py

This file contains the generated configuration of your rest_api. You can continue with the next steps and leave it as is, but you might want to come back here and make adjustments if you need your rest_api source set up in a different way. The generated file for the klarna source will look like this:

Click to view full file (39 lines)

from typing import List

import dlt
from dlt.extract.source import DltResource
from rest_api import rest_api_source
from rest_api.typing import RESTAPIConfig


@dlt.source(name="klarna_source", max_table_nesting=2)
def klarna_source(
base_url: str = dlt.config.value,
) -> List[DltResource]:

# source configuration
source_config: RESTAPIConfig = {
"client": {
"base_url": base_url,
},
"resources":
[
# Use this API call to get a Klarna Payments session. You can read the Klarna Payments session at any time after it has been created, to get information about it. This will return all data that has been collected during the session. Read more on **[Read an existing payment session](https://docs.klarna.com/klarna-payments/other-actions/check-the-details-of-a-payment-session/)**.
{
"name": "session_read",
"table_name": "session_read",
"endpoint": {
"data_selector": "$",
"path": "/payments/v1/sessions/{session_id}",
"params": {
"session_id": "FILL_ME_IN", # TODO: fill in required path parameter

},
"paginator": "auto",
}
},
]
}

return rest_api_source(source_config)

2. Configuring your source and destination credentials

info

dlt-init-openapi will try to detect which authentication mechanism (if any) is used by the API in question and add a placeholder in your secrets.toml.

  • If you know your API needs authentication, but none was detected, you can learn more about adding authentication to the rest_api here.
  • OAuth detection currently is not supported, but you can supply your own authentication mechanism as outlined here.

The dlt cli will have created a .dlt directory in your project folder. This directory contains a config.toml file and a secrets.toml file that you can use to configure your pipeline. The automatically created version of these files look like this:

generated config.toml


[runtime]
log_level="INFO"

[sources.klarna]
# Base URL for the API
base_url = "https://api.klarna.com"

generated secrets.toml


[sources.klarna]
# secrets for your klarna source
# example_api_key = "example value"

2.1. Adjust the generated code to your usecase

Further help setting up your source and destinations

At this time, the dlt-init-openapi cli tool will always create pipelines that load to a local duckdb instance. Switching to a different destination is trivial, all you need to do is change the destination parameter in klarna_pipeline.py to postgres and supply the credentials as outlined in the destination doc linked below.

  • Read more about setting up the rest_api source in our docs.
  • Read more about setting up the CockroachDB destination in our docs.

3. Running your pipeline for the first time

The dlt cli has also created a main pipeline script for you at klarna_pipeline.py, as well as a folder klarna that contains additional python files for your source. These files are your local copies which you can modify to fit your needs. In some cases you may find that you only need to do small changes to your pipelines or add some configurations, in other cases these files can serve as a working starting point for your code, but will need to be adjusted to do what you need them to do.

The main pipeline script will look something like this:


import dlt

from klarna import klarna_source


if __name__ == "__main__":
pipeline = dlt.pipeline(
pipeline_name="klarna_pipeline",
destination='duckdb',
dataset_name="klarna_data",
progress="log",
export_schema_path="schemas/export"
)
source = klarna_source()
info = pipeline.run(source)
print(info)

Provided you have set up your credentials, you can run your pipeline like a regular python script with the following command:

python klarna_pipeline.py

4. Inspecting your load result

You can now inspect the state of your pipeline with the dlt cli:

dlt pipeline klarna_pipeline info

You can also use streamlit to inspect the contents of your CockroachDB destination for this:

# install streamlit
pip install streamlit
# run the streamlit app for your pipeline with the dlt cli:
dlt pipeline klarna_pipeline show

5. Next steps to get your pipeline running in production

One of the beauties of dlt is, that we are just a plain Python library, so you can run your pipeline in any environment that supports Python >= 3.8. We have a couple of helpers and guides in our docs to get you there:

The Deploy section will show you how to deploy your pipeline to

  • Deploy with GitHub Actions: Learn how to deploy your pipeline using GitHub Actions for automated CI/CD. Follow the guide here.
  • Deploy with Airflow: Discover how to deploy your pipeline with Airflow and Google Composer. Detailed instructions can be found here.
  • Deploy with Google Cloud Functions: Explore the steps to deploy your pipeline using Google Cloud Functions. Check the guide here.
  • Other Deployment Options: Find more deployment options and detailed walkthroughs here.

The running in production section will teach you about:

  • How to Monitor your pipeline: Learn how to effectively monitor your dlt pipeline to ensure smooth operation and quick identification of issues. How to Monitor your pipeline
  • Set up alerts: Set up alerts to stay informed about the status of your dlt pipeline and quickly respond to any issues that arise. Set up alerts
  • And set up tracing: Implement tracing to get detailed insights into the execution of your dlt pipeline, helping you to debug and optimize performance. And set up tracing

Available Sources and Resources

For this verified source the following sources and resources are available

Source Klarna

Klarna source for accessing session data and related analytics.

Resource NameWrite DispositionDescription
session_readappendSession data including user interactions and payment sessions

Additional pipeline guides

This demo works on codespaces. Codespaces is a development environment available for free to anyone with a Github account. You'll be asked to fork the demo repository and from there the README guides you with further steps.
The demo uses the Continue VSCode extension.

Off to codespaces!

DHelp

Ask a question

Welcome to "Codex Central", your next-gen help center, driven by OpenAI's GPT-4 model. It's more than just a forum or a FAQ hub – it's a dynamic knowledge base where coders can find AI-assisted solutions to their pressing problems. With GPT-4's powerful comprehension and predictive abilities, Codex Central provides instantaneous issue resolution, insightful debugging, and personalized guidance. Get your code running smoothly with the unparalleled support at Codex Central - coding help reimagined with AI prowess.