Every data pipeline starts with the same challenge: getting your code to reliably talk to the systems where data lives. This lesson walks you through connecting to relational databases, REST APIs, and cloud storage in Python — with real code, proper credential management, and the habits that make connections production-ready.

Every data pipeline starts with the same fundamental challenge: getting your code to actually talk to the systems where data lives. You can design the most elegant transformation logic in the world, but if you can't reliably connect to your PostgreSQL database, authenticate with your company's REST API, or pull files from an S3 bucket, you have nothing. For many beginners, this first step — the unglamorous work of establishing connections and handling credentials — is where they get stuck and give up.
This lesson is about removing that friction. We'll work through the three most common data source categories you'll encounter in real pipelines: relational databases, HTTP APIs, and cloud object storage. For each one, you'll understand not just the mechanics of connecting, but why authentication works the way it does, what can go wrong, and how to structure your code so it stays secure and maintainable as your pipeline grows.
By the end of this lesson, you'll have working Python code for each source type, a solid mental model of how credentials flow through a pipeline, and the habits that separate sloppy connection code from production-ready code.
What you'll learn:
.env filesYou should be comfortable with basic Python — writing functions, working with dictionaries, and importing libraries. You don't need any prior data engineering experience, but familiarity with what a data pipeline does will help. If you're new to pipelines entirely, What is a Data Pipeline? Architecture and Core Concepts for Data Engineers is the right starting point.
You'll need Python 3.8+ installed, along with the ability to pip install packages.
Before we touch a single data source, we need to establish one rule that you will follow for the rest of your career: credentials never live in source code. Not in a string literal. Not in a comment. Not in a variable named password. Nowhere.
Here's why this matters more than it might seem. Source code gets committed to version control. Version control gets pushed to GitHub. GitHub repositories get made public by accident, shared with contractors, or breached. When credentials are embedded in code, a single mistake exposes your entire data infrastructure.
The correct approach is to store credentials in environment variables — values that exist in the operating system's environment, not in any file your pipeline reads. Python's os module can read them, and the python-dotenv library lets you define them in a local .env file that never gets committed.
Install the library first:
pip install python-dotenv
Create a .env file in your project root:
DB_HOST=db.yourcompany.com
DB_PORT=5432
DB_NAME=sales_data
DB_USER=pipeline_user
DB_PASSWORD=s3cr3tpassword
Immediately add .env to your .gitignore:
# .gitignore
.env
Then in your Python code, load those variables before anything else:
import os
from dotenv import load_dotenv
load_dotenv() # Reads .env into environment variables
db_host = os.getenv("DB_HOST")
db_password = os.getenv("DB_PASSWORD")
Warning
If you accidentally commit a .env file or hardcoded credentials to a public repository, rotating the credentials immediately is not optional — it's urgent. Even if you delete the file in a subsequent commit, the credentials remain visible in git history. For a deeper treatment of this topic in production contexts, see Secrets Management and Credential Rotation for Data Pipelines in Production.
This pattern — load from environment, never hardcode — applies to every data source we'll cover. Keep it in mind as we work through each one.
Relational databases like PostgreSQL, MySQL, and SQLite are the most common data source for pipeline beginners. Your company's transactional system almost certainly stores data in one. The good news is that connecting to them from Python is well-supported and predictable once you understand the pattern.
A connection string (also called a DSN, or Data Source Name) is a single string that encodes everything needed to reach a database: the driver, hostname, port, database name, username, and password. It follows a URL-like format:
postgresql://username:password@hostname:port/database_name
For example, connecting to a PostgreSQL database that holds e-commerce order data:
postgresql://pipeline_user:s3cr3tpassword@db.mystore.com:5432/orders_db
You'll see this format used directly by libraries like SQLAlchemy, which provides a consistent interface regardless of which database you're connecting to.
Install the dependencies:
pip install sqlalchemy psycopg2-binary
SQLAlchemy is the abstraction layer. psycopg2 is the PostgreSQL-specific driver it uses under the hood.
import os
from dotenv import load_dotenv
from sqlalchemy import create_engine, text
load_dotenv()
def get_db_engine():
"""Create and return a database engine using environment variables."""
connection_string = (
f"postgresql://{os.getenv('DB_USER')}:{os.getenv('DB_PASSWORD')}"
f"@{os.getenv('DB_HOST')}:{os.getenv('DB_PORT')}/{os.getenv('DB_NAME')}"
)
engine = create_engine(connection_string, pool_pre_ping=True)
return engine
def fetch_recent_orders(days_back: int = 7):
"""Fetch orders placed in the last N days."""
engine = get_db_engine()
query = text("""
SELECT order_id, customer_id, total_amount, created_at
FROM orders
WHERE created_at >= NOW() - INTERVAL ':days days'
ORDER BY created_at DESC
""")
with engine.connect() as connection:
result = connection.execute(query, {"days": days_back})
rows = result.fetchall()
return rows
if __name__ == "__main__":
orders = fetch_recent_orders(days_back=7)
print(f"Fetched {len(orders)} orders from the past week.")
A few things to notice in this code. First, get_db_engine() builds the connection string entirely from environment variables — no hardcoded values. Second, we use pool_pre_ping=True, which tells SQLAlchemy to verify the connection is alive before using it from its internal pool. This prevents mysterious failures when a database connection has been idle too long and the server closed it. Third, we use a with engine.connect() as connection: context manager, which guarantees the connection is properly closed even if an exception occurs.
If you're pulling data into a DataFrame for transformation, pandas integrates directly with SQLAlchemy engines:
import pandas as pd
def load_orders_as_dataframe(days_back: int = 7):
engine = get_db_engine()
query = f"""
SELECT order_id, customer_id, total_amount, created_at
FROM orders
WHERE created_at >= NOW() - INTERVAL '{days_back} days'
"""
df = pd.read_sql(query, engine)
return df
Tip
For large tables, avoid SELECT * and always filter with a WHERE clause. Pulling an entire production table when you only need recent records wastes memory and time, and it can lock up the database server if your query runs at peak hours. This connects directly to Incremental Loading Patterns: Timestamps, CDC, and Watermarks, which covers the right strategies for pulling only new data.
APIs (Application Programming Interfaces) are how most modern services expose their data. Whether you're pulling CRM records from Salesforce, event data from Mixpanel, or weather data from a public source, you're likely talking to a REST API over HTTP. The connection mechanism is different from databases — instead of a persistent session, you send individual HTTP requests and receive responses.
APIs use several authentication schemes, and knowing which one you're dealing with shapes how you write your connection code.
API Key — A single string passed in a request header or query parameter. Simple but common.
Bearer Token — A token (often a JWT) passed in the Authorization header. Tokens are often short-lived and need to be refreshed.
Basic Auth — Username and password encoded in the Authorization header. Less common for modern APIs but still used.
OAuth 2.0 — A multi-step flow where you exchange credentials for a token. Used by Google, Salesforce, Slack, and many others. We'll keep this out of scope for now, as it deserves its own lesson.
This is the most common pattern for data APIs. Let's say you're pulling product review data from a fictional analytics platform:
pip install requests
import os
import requests
from dotenv import load_dotenv
load_dotenv()
API_BASE_URL = "https://api.reviewplatform.com/v1"
def get_api_headers():
"""Return headers with API key for authentication."""
return {
"X-API-Key": os.getenv("REVIEW_API_KEY"),
"Accept": "application/json",
"Content-Type": "application/json"
}
def fetch_product_reviews(product_id: str, page: int = 1):
"""Fetch reviews for a given product from the API."""
url = f"{API_BASE_URL}/products/{product_id}/reviews"
params = {"page": page, "per_page": 100}
response = requests.get(url, headers=get_api_headers(), params=params)
response.raise_for_status() # Raises an exception for 4xx/5xx status codes
return response.json()
# Usage
reviews = fetch_product_reviews(product_id="SKU-7842")
print(f"Retrieved {len(reviews['data'])} reviews.")
The raise_for_status() call is critical. Without it, a 401 Unauthorized or 403 Forbidden response would look like a successful call — your code would continue running and try to process an error message as if it were real data. raise_for_status() turns HTTP error codes into Python exceptions so you can catch them explicitly.
Some APIs require you to first exchange credentials for a temporary token, then use that token for subsequent requests. This two-step pattern is common:
import os
import requests
from dotenv import load_dotenv
load_dotenv()
AUTH_URL = "https://api.crm-platform.com/oauth/token"
API_BASE_URL = "https://api.crm-platform.com/v2"
def get_bearer_token():
"""Exchange client credentials for a bearer token."""
response = requests.post(AUTH_URL, data={
"grant_type": "client_credentials",
"client_id": os.getenv("CRM_CLIENT_ID"),
"client_secret": os.getenv("CRM_CLIENT_SECRET")
})
response.raise_for_status()
token_data = response.json()
return token_data["access_token"]
def fetch_contacts(token: str, modified_since: str = None):
"""Fetch contact records from the CRM."""
headers = {"Authorization": f"Bearer {token}"}
params = {}
if modified_since:
params["modified_since"] = modified_since
response = requests.get(
f"{API_BASE_URL}/contacts",
headers=headers,
params=params
)
response.raise_for_status()
return response.json()
# Usage
token = get_bearer_token()
contacts = fetch_contacts(token, modified_since="2024-01-01")
Note
Bearer tokens often expire after an hour or less. For long-running pipelines that make many API calls, you'll need to refresh the token when it expires. The Working with APIs: REST, Pagination, and Rate Limiting for Data Engineers lesson covers building resilient API clients that handle pagination and token refresh automatically.
Before you write your first real pipeline against an API, memorize these response codes:
| Code | Meaning | Your Action |
|---|---|---|
| 200 | OK — Success | Process the data |
| 400 | Bad Request | Check your query parameters |
| 401 | Unauthorized | Check your credentials |
| 403 | Forbidden | Your key doesn't have permission |
| 404 | Not Found | The endpoint or resource doesn't exist |
| 429 | Too Many Requests | You're being rate-limited — slow down |
| 500 | Server Error | Retry with backoff |
Tip
A 401 means your credentials are wrong or missing. A 403 means your credentials are valid but your account doesn't have permission to access that resource. These look similar but have very different fixes. 401 means fix your authentication. 403 means contact the API owner to request access.
Cloud storage services like AWS S3, Google Cloud Storage (GCS), and Azure Blob Storage are where modern data pipelines store raw files — CSVs, JSON dumps, Parquet files, and more. Unlike databases, cloud storage doesn't have a query engine — you read and write files using an SDK (Software Development Kit) provided by the cloud provider.
For a broader look at how these systems fit into pipeline ingestion patterns, see Connecting to Databases, Flat Files, and Cloud Storage for Data Pipeline Ingestion. Here, we'll focus specifically on authentication and connection mechanics.
AWS S3 is by far the most common cloud storage system in data engineering. The Python library for interacting with AWS is boto3.
pip install boto3
AWS authentication is more layered than a simple API key. You have:
us-east-1)import os
import boto3
from dotenv import load_dotenv
load_dotenv()
def get_s3_client():
"""Create an authenticated S3 client."""
return boto3.client(
"s3",
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
region_name=os.getenv("AWS_REGION", "us-east-1")
)
def list_files_in_bucket(bucket_name: str, prefix: str = ""):
"""List all files in an S3 bucket under a given prefix."""
s3 = get_s3_client()
response = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
if "Contents" not in response:
print(f"No files found in s3://{bucket_name}/{prefix}")
return []
return [obj["Key"] for obj in response["Contents"]]
def download_file_to_memory(bucket_name: str, file_key: str):
"""Download a file from S3 and return its contents as bytes."""
s3 = get_s3_client()
response = s3.get_object(Bucket=bucket_name, Key=file_key)
file_contents = response["Body"].read()
return file_contents
# Usage: read a CSV from S3 into a pandas DataFrame
import pandas as pd
import io
def read_csv_from_s3(bucket_name: str, file_key: str):
"""Read a CSV file from S3 directly into a DataFrame."""
raw_bytes = download_file_to_memory(bucket_name, file_key)
df = pd.read_csv(io.BytesIO(raw_bytes))
return df
# Example
df = read_csv_from_s3("my-data-lake", "raw/sales/2024-01-15/transactions.csv")
print(f"Loaded {len(df)} rows from S3.")
The io.BytesIO wrapper lets pandas treat the raw bytes from S3 as if they were a file on disk. This is a standard pattern for reading cloud-stored files without saving them locally first.
Hardcoding access keys — even in environment variables — is fine for local development, but in production, the preferred approach is to use IAM roles. When your pipeline runs on an EC2 instance, Lambda function, or ECS container, you can assign an IAM role to that compute resource. The code then authenticates automatically without any credentials in environment variables at all.
def get_s3_client_using_role():
"""
When running on AWS infrastructure with an IAM role attached,
boto3 picks up credentials automatically from the environment.
No keys needed.
"""
return boto3.client("s3", region_name="us-east-1")
When you call boto3.client() without explicit credentials, the library looks for credentials in this order: environment variables, ~/.aws/credentials file, IAM role attached to the running instance. This automatic lookup chain is called the credential provider chain, and it's the right way to handle AWS authentication in production.
Key insight
For local development, use environment variables with a .env file. For production pipelines running on cloud infrastructure, use IAM roles or service accounts — no access keys anywhere. This principle applies to GCS (use service account JSON files or Workload Identity) and Azure Blob Storage (use Managed Identity) as well.
In this exercise, you'll build a small pipeline that reads customer data from two sources and combines them. Even if you don't have real credentials for all three source types right now, you can practice the structure with what you have available.
Setup: Create a project folder with the following structure:
pipeline_exercise/
├── .env
├── .gitignore
├── connectors.py
└── pipeline.py
Step 1: Add your credentials to .env (use whatever you have — a local SQLite database, a public API, etc.):
# .env
DB_HOST=localhost
DB_PORT=5432
DB_NAME=testdb
DB_USER=postgres
DB_PASSWORD=yourpassword
WEATHER_API_KEY=your_key_here
AWS_ACCESS_KEY_ID=your_key
AWS_SECRET_ACCESS_KEY=your_secret
AWS_REGION=us-east-1
Step 2: In connectors.py, write three functions — one for each source type — that each return a list or DataFrame when called. Use the patterns from this lesson.
Step 3: In pipeline.py, call each connector and print how many records you retrieved from each source.
Step 4: Add error handling so that if one connector fails (bad credentials, network issue), the pipeline prints a clear error message and continues to try the other sources.
This exercise mirrors what you'd do at the start of Building Your First Data Pipeline with Python — the connectors you write here will be the foundation for everything that comes next.
"Authentication failed" but credentials look correct
Double-check for invisible whitespace. When you copy-paste API keys from a browser or email, trailing spaces or newline characters can get included. Print repr(os.getenv("API_KEY")) to see the raw string — if you see \n or a space at the end, your .env file has whitespace issues.
load_dotenv() isn't finding the .env file
By default, load_dotenv() looks for .env in the current working directory, which is wherever you ran python from — not necessarily where your script lives. Use load_dotenv(dotenv_path="/absolute/path/to/.env") or run your script from the project root.
Database connection times out immediately
This usually means the hostname is unreachable, not that your credentials are wrong. Check whether you need to be on a VPN or whether the database's firewall allows connections from your IP. Try ping db.yourcompany.com from the terminal as a quick sanity check.
S3 returns "NoCredentialsError" even with environment variables set
The variable names must be exactly AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY — boto3 looks for these specific names as part of its credential provider chain. Also confirm load_dotenv() is being called before the boto3 client is created.
API returns 429 Too Many Requests
You're hitting the API faster than it allows. Add a time.sleep(1) between requests as a quick fix, or implement proper exponential backoff for a production pipeline. For a thorough treatment of this, see Pipeline Retry Logic and Exponential Backoff: Handling Transient Failures in Data Pipelines.
Connection works locally but fails in CI/CD or production
Your environment variables are set in your .env file, but that file doesn't exist in production. You need to inject the variables through your deployment platform — GitHub Actions secrets, AWS Parameter Store, Kubernetes secrets, or similar. The .env file is for local development only.
Warning
A silent failure is worse than a loud crash. If your database query returns zero rows because of a permissions issue, your pipeline might not raise an error — it'll just process an empty dataset and produce silently wrong output. Always validate that you got a reasonable number of records before proceeding. This connects to the broader topic of Data Quality: Validation, Testing, and Monitoring Pipelines.
You now have the foundation for connecting to the three most common data source types in real pipelines. Let's consolidate what you've built:
python-dotenv locally and injected by your platform in production. Never in code.pool_pre_ping=True to handle connection lifecycle properly.raise_for_status() to surface HTTP errors.boto3, with IAM roles as the production-grade authentication approach and explicit access keys only for local development.These patterns compose. A real pipeline might read configuration from S3, fetch supplemental data from an API, query a database for the main dataset, and write the result back to both a database and S3 — all in one run. Each connection follows the same principles you learned here.
Where to go next:
Data Pipeline Fundamentals