Skip to main content

Apache Airflow® Tutorial for Data Pipelines in Python — Part 1: Install Airflow and Run Your First Dag

· 19 min read
Jagdish Kumawat
Founder @ Dewiride

A data pipeline that runs on a timer is easy to start and hard to trust: did last night's run work, what did it do, and can it run again for the day it missed? Apache Airflow® is built to answer those questions. This series builds a real pipeline with it, step by step, on your own computer. In Part 1 you install Airflow, start it, and run your first Dag: a task that counts yesterday's earthquakes worldwide.

This is Part 1 of the series.

  1. Part 1: Install Airflow and Run Your First Dag (you are here)

Every command and output on this page is real, captured while building the project.

What You'll Have at the End of the Series​

Each part teaches one part of Airflow, on the same pipeline: earthquake data from the U.S. Geological Survey (USGS), loaded into PostgreSQL. By the end you'll know how to:

  • install and run Airflow, and write and run a Dag (this part);
  • connect tasks and pass data between them;
  • schedule a pipeline, and make each run handle exactly its own time window;
  • catch up on missed runs and re-run past ones safely;
  • keep settings and connections out of your code;
  • load data into PostgreSQL with Airflow's providers;
  • retry failures and get alerts;
  • branch a pipeline and group tasks;
  • create tasks dynamically, one per item;
  • wait for things outside Airflow without holding a worker;
  • start pipelines when data arrives, not on a clock;
  • run Airflow on PostgreSQL with each part separate, as production does;
  • and finish with a production checklist.

What Apache Airflow® Is​

Airflow is a platform for running workflows written in Python. You describe a workflow as a Dag, a set of tasks and the order they run in, and Airflow runs it: on a schedule or by hand, with retries, with a record of every run, and with a web UI to watch and control it all. Older material writes DAG, short for directed acyclic graph; Airflow 3's documentation and UI write Dag.

Compared with a cron job, which only starts a command at a time, Airflow also knows whether each run worked, can re-run a past day, waits for a task's inputs before starting it, and shows you the log of every attempt.

How Airflow 3 Is Put Together​

Airflow isn't one program but several, which the architecture overview in Airflow's documentation describes:

PartWhat it does
API serverServes the web UI and the REST API. Running tasks also report back to it, through the Task SDK
Dag processorReads your Dag files and stores each Dag in the metadata database
SchedulerDecides what should run and when, and hands tasks to its executor, which runs them
TriggererRuns tasks that wait for something, without holding a worker
Metadata databaseStores Dags, runs, task states and settings

In this part, one command starts all of them, and the database is a single SQLite file. A later part runs each of them on its own, on PostgreSQL.

The Example: Yesterday's Earthquakes​

USGS publishes every earthquake it records worldwide through a free web API that needs no key. The pipeline in this series reads it. In this part, a single task asks the API how many earthquakes happened yesterday, UTC, and writes the number to its log. How to Query the USGS Earthquake API with curl shows the API on its own.

What This Part Costs​

Nothing. Airflow is open source under the Apache License 2.0, uv and Python are free, and the USGS API is free and public. Everything runs on your own computer.

Prerequisites​

  • uv. Check with uv --version. This part uses uv 0.13.10.
  • On Windows, a WSL2 terminal. Airflow doesn't run on Windows directly; its prerequisites page says to use WSL2. Every command here is for bash or zsh.

Step 1: Create the Project and Its Virtual Environment​

Terminal
mkdir dewiride-earthquake-pipeline
cd dewiride-earthquake-pipeline
uv venv --python 3.14
Output
Using CPython 3.14.10
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate

The terminal after uv venv --python 3.14: Using CPython 3.14.10, Creating virtual environment at .venv.

The project folder holds everything in this series. .venv is its own Python with its own packages. Python 3.14 is the newest version Airflow 3.4.0 supports; uv downloads it if you don't have it.

Step 2: Install Apache Airflow® with Its Constraints File​

Terminal
source .venv/bin/activate
AIRFLOW_VERSION=3.4.0
PYTHON_VERSION="$(python -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
CONSTRAINT_URL="https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt"
echo "$CONSTRAINT_URL"
uv pip install "apache-airflow==${AIRFLOW_VERSION}" --constraint "${CONSTRAINT_URL}"
Output (excerpt)
https://raw.githubusercontent.com/apache/airflow/constraints-3.4.0/constraints-3.14.txt
Resolved 132 packages in 4.40s
Prepared 132 packages in 5.78s
Installed 132 packages in 166ms
+ a2wsgi==1.10.10
...
+ apache-airflow==3.4.0
+ apache-airflow-core==3.4.0
...
+ apache-airflow-task-sdk==1.4.0
...

The terminal after the install: the constraints URL for Airflow 3.4.0 and Python 3.14, then Resolved, Prepared and Installed 132 packages.

These lines come from Airflow's Quick Start. The constraints file pins each of the 132 packages to the version Airflow 3.4.0 was tested with, so your installation matches the one the Airflow team tested. How to Install Apache Airflow® with uv and a Constraints File explains each line.

Step 3: Keep Airflow's Files in the Project​

Terminal
export AIRFLOW_HOME="$PWD"
airflow version
Output
3.4.0

The terminal after airflow version: 3.4.0.

AIRFLOW_HOME is where Airflow keeps its settings, database and logs. Without it, Airflow uses ~/airflow, one folder shared by every project; pointing it at the project keeps everything together. Run the export line in every new terminal you use for this project (How to Set AIRFLOW_HOME for Apache Airflow®).

On Python 3.14, every airflow command first prints two FileType is deprecated warning lines. They don't affect anything, and I leave them out of the outputs from here on.

Step 4: Create the dags Folder and airflow.cfg​

Terminal
mkdir dags
airflow config get-value api port
Output
8080

The terminal after mkdir dags and airflow config get-value api port: 8080.

dags is where your Dag files go. Create it now, because Airflow doesn't, and without it Airflow starts with a warning (Fixed: Bundle 'dags-folder' path does not exist).

The second command reads one setting, the API server's port, and as the first command that needs settings, it also wrote airflow.cfg into the project: a file with every setting and its description. Its logs folder appeared too.

Step 5: Change Four Settings​

Open airflow.cfg in your editor and change these four values, each in its own section:

airflow.cfg (the four changed lines)
[core]
load_examples = False

[api]
host = 127.0.0.1
port = 8085

[api_auth]
jwt_secret = <86 random characters, made with the command below>
SettingWhy
load_examples = FalseSkips the 119 example Dags, so the Dags page shows only yours (How to Turn Off the Example Dags in Apache Airflow®)
host = 127.0.0.1The UI answers only on this computer, instead of on every network address
port = 8085Port 8080, the default, is often taken by another program (How to Change the Port and Host of the Apache Airflow® API Server)
jwt_secretThe key Airflow signs its access tokens with. The one it generates is too short for its algorithm and causes a warning (Fixed: The HMAC key is 24 bytes long)

Generate the secret with Python's secrets module and paste it in as the value:

Terminal
python -c "import secrets; print(secrets.token_urlsafe(64))"
Output
<86 random characters; mine is hidden here>

Check the three readable ones:

Terminal
airflow config get-value api host
airflow config get-value api port
airflow config get-value core load_examples
Output
127.0.0.1
8085
False

The terminal: airflow config get-value prints 127.0.0.1 for api host, 8085 for api port and False for core load_examples.

airflow.cfg now holds a secret, so it must never go into Git; Step 11 makes sure it doesn't.

Step 6: Start Airflow​

Terminal
airflow standalone
Output (excerpt)
standalone | Starting Airflow Standalone
standalone | Checking for new Dag files every 5 seconds (set [dag_processor] refresh_interval to change this)
Simple auth manager | Password for user 'admin': ********
standalone | Checking database is initialized
...
standalone | Database ready
...
api-server | 2026-12-01T03:16:34.617425Z [info ] Uvicorn running on http://127.0.0.1:8085 (Press CTRL+C to quit) [uvicorn.error] loc=server.py:234
standalone | Airflow is ready
standalone | Airflow Standalone is for development purposes only. Do not use this in production!

The airflow standalone output: Starting Airflow Standalone, the admin password (hidden here), Database ready, the API server running on http://127.0.0.1:8085, and Airflow is ready.

airflow standalone starts every part from the diagram above in this one terminal, each line prefixed with the part that printed it. On this first start it created the database and an admin user with a random password, printed once. Leave the terminal running (How to Start Apache Airflow® on Your Computer with airflow standalone).

To read the password again later, open a second terminal in the project, export AIRFLOW_HOME there too, and print the file Airflow keeps it in:

Terminal
cat "${AIRFLOW_HOME:-$HOME/airflow}/simple_auth_manager_passwords.json.generated"
Output
{"admin": "********"}

The terminal after cat of the passwords file: one line of JSON with the user admin and its password, replaced by stars.

How to Find the Admin Password for Apache Airflow® standalone explains the file.

Step 7: Sign In and Look Around​

Open http://127.0.0.1:8085 and sign in as admin:

The Apache Airflow® sign-in form with admin as the username, the password shown as dots, the Sign in button and the Simple auth manager enabled note.

The first page is Welcome:

The Welcome page: Stats with 0 failed, running and active Dags, and the Health section with MetaDatabase, Scheduler, Triggerer and Dag Processor all green.

The Health row shows the metadata database, the scheduler, the triggerer and the Dag processor all running. Click Dags in the menu on the left:

The Dags page with 0 Dags and the message No Dags found.

Empty, because the examples are off and you haven't written a Dag yet.

Step 8: Write Your First Dag​

Create dags/earthquake_count.py. It's built with Airflow's TaskFlow style, where Dags and tasks are plain Python functions (How to Write a Dag with the TaskFlow API in Apache Airflow®). Piece by piece:

dags/earthquake_count.py
"""Count yesterday's earthquakes worldwide with the USGS earthquake API."""

import json
import logging
from datetime import UTC, datetime, timedelta
from urllib.parse import urlencode
from urllib.request import urlopen

from airflow.sdk import dag, task

Everything here except the last line comes with Python: json reads the API's answer, logging writes to the task's log, datetime works out yesterday's date, and urllib builds the address and calls the API. dag and task come from Airflow's Task SDK.

dags/earthquake_count.py
USGS_COUNT_URL = "https://earthquake.usgs.gov/fdsnws/event/1/count"

log = logging.getLogger(__name__)

The address of the API's count method, and a logger for the task's messages.

dags/earthquake_count.py
@dag(schedule=None, tags=["earthquakes"])
def earthquake_count():
"""Count the earthquakes that USGS recorded worldwide yesterday (UTC)."""

@dag makes the function a Dag whose ID is its name, earthquake_count. schedule=None means it only runs when you trigger it; a later part gives it a schedule.

dags/earthquake_count.py
@task
def count_yesterdays_earthquakes() -> int:
today = datetime.now(UTC).date()
yesterday = today - timedelta(days=1)

@task makes the function a task. It takes today's date in UTC, the time zone the USGS API uses, and subtracts one day.

dags/earthquake_count.py
query = urlencode(
{
"format": "geojson",
"eventtype": "earthquake",
"starttime": yesterday.isoformat(),
"endtime": today.isoformat(),
}
)

The question for the API: earthquakes only, from the start of yesterday to the start of today, with the answer as JSON. urlencode turns the dictionary into format=geojson&eventtype=earthquake&…, and isoformat() writes a date as 2026-11-30.

dags/earthquake_count.py
with urlopen(f"{USGS_COUNT_URL}?{query}", timeout=30) as response:
count = json.load(response)["count"]
log.info("USGS recorded %d earthquakes on %s (UTC).", count, yesterday)
return count

The task calls the API, waiting at most 30 seconds, reads the JSON answer and takes its count. It writes the number to the log and returns it, which stores it in Airflow for later tasks to use.

dags/earthquake_count.py
count_yesterdays_earthquakes()


earthquake_count()

The first line adds the task to the Dag. The last line calls the Dag function, which is what creates the Dag for Airflow to find.

The complete file:

dags/earthquake_count.py
"""Count yesterday's earthquakes worldwide with the USGS earthquake API."""

import json
import logging
from datetime import UTC, datetime, timedelta
from urllib.parse import urlencode
from urllib.request import urlopen

from airflow.sdk import dag, task

USGS_COUNT_URL = "https://earthquake.usgs.gov/fdsnws/event/1/count"

log = logging.getLogger(__name__)


@dag(schedule=None, tags=["earthquakes"])
def earthquake_count():
"""Count the earthquakes that USGS recorded worldwide yesterday (UTC)."""

@task
def count_yesterdays_earthquakes() -> int:
today = datetime.now(UTC).date()
yesterday = today - timedelta(days=1)
query = urlencode(
{
"format": "geojson",
"eventtype": "earthquake",
"starttime": yesterday.isoformat(),
"endtime": today.isoformat(),
}
)
with urlopen(f"{USGS_COUNT_URL}?{query}", timeout=30) as response:
count = json.load(response)["count"]
log.info("USGS recorded %d earthquakes on %s (UTC).", count, yesterday)
return count

count_yesterdays_earthquakes()


earthquake_count()

The earthquake_count.py Dag file in an editor window: the imports, the USGS count URL, the earthquake_count Dag and its count_yesterdays_earthquakes task, which asks the USGS API for yesterday's count and logs it.

That's the whole Dag: one task, in about 40 lines of plain Python.

Step 9: Run It​

Save the file. Within a few seconds the Dag processor finds it; in the airflow standalone terminal:

Output (excerpt)
dag-processor | 2026-12-01T03:17:13.670276Z [info ] Found 1 files for bundle dags-folder (dag_discovery_safe_mode=True) [airflow.dag_processing.manager.DagFileProcessorManager] loc=manager.py:1033
dag-processor | 2026-12-01T03:17:15.601942Z [info ] Creating ORM DAG for earthquake_count [airflow.dag_processing.collection] loc=collection.py:104

Back on the Dags page:

The Dags page with 1 Dag: earthquake_count, tagged earthquakes, with its pause toggle off.

earthquake_count is there, paused, as every new Dag is. Click the ▷ button in its row:

The Trigger Dag - earthquake_count dialog: Single Run selected, the Logical Date, and Unpause selected under Dag is paused, with the Trigger button at the bottom.

Keep Single Run and Unpause, and click Trigger. The dialog starts one run and unpauses the Dag on the way (How to Trigger a Dag from the Apache Airflow® UI).

Step 10: Read the Result​

Click the Dag's name to open its page:

The earthquake_count Dag page: Latest Run 2026-12-01 03:17:31 with a green check, the toggle on, and count_yesterdays_earthquakes green in the grid.

The run succeeded. Click the green square of count_yesterdays_earthquakes in the grid to see its log:

The log of the count_yesterdays_earthquakes task: Success in 3.84 seconds, and the lines INFO - USGS recorded 338 earthquakes on 2026-11-30 (UTC). and INFO - Done. Returned value was: 338.

USGS recorded 338 earthquakes on 2026-11-30 (UTC). That's your Dag's log.info line, and Done. Returned value was: 338 is Airflow noting the value the task returned. USGS keeps reviewing its catalog, so the same day can give a slightly different count later. How to Read a Task Log in the Apache Airflow® UI explains the rest of the page.

Step 11: Put the Project in Git​

Your Dag is code worth keeping; most of what Airflow wrote into the project isn't, and airflow.cfg and the password file are secrets. Create .gitignore in the project folder first:

.gitignore
# Python
.venv/
__pycache__/

# Files Airflow creates in AIRFLOW_HOME (this folder). airflow.cfg holds generated
# secrets, so it never goes into Git.
airflow.cfg
airflow.db
airflow.db-*
logs/
simple_auth_manager_passwords.json.generated

Then, in the second terminal:

Terminal
git init -b main
git status --short --ignored
Output
Initialized empty Git repository in /Users/you/source/dewiride-earthquake-pipeline/.git/
?? .gitignore
?? dags/
!! .venv/
!! airflow.cfg
!! airflow.db
!! airflow.db-shm
!! airflow.db-wal
!! logs/
!! simple_auth_manager_passwords.json.generated

Only .gitignore and dags/ are untracked (??); everything Airflow made is ignored (!!). airflow.db-shm and airflow.db-wal exist while Airflow runs. Commit:

Terminal
git add .
git commit -m "Count yesterday's earthquakes with a first Dag"
Output
[main (root-commit) 11474fe] Count yesterday's earthquakes with a first Dag
2 files changed, 51 insertions(+)
create mode 100644 .gitignore
create mode 100644 dags/earthquake_count.py

The terminal: git init, git status --short --ignored with only .gitignore and dags untracked and every Airflow file ignored, then the first commit with .gitignore and dags/earthquake_count.py.

Two files went in, and nothing secret. How to Keep Apache Airflow® Files Out of Git with .gitignore explains each line.

Your Project Now Looks Like This​

dewiride-earthquake-pipeline
dewiride-earthquake-pipeline/
├── .git/
├── .gitignore
├── .venv/
├── airflow.cfg
├── airflow.db
├── dags/
│ └── earthquake_count.py
├── logs/
└── simple_auth_manager_passwords.json.generated

Stop Airflow When You're Done​

In the airflow standalone terminal, press Ctrl+C:

Output
^Cstandalone | Shutting down components
standalone | Complete

Complete means every part has stopped. To start again later, open a terminal in the project folder and run source .venv/bin/activate, export AIRFLOW_HOME="$PWD" and airflow standalone: the database, the password and your Dag are all still there.

If you won't continue with the series, delete the dewiride-earthquake-pipeline folder: everything this part created is inside it.

Common Mistakes​

MistakeWhat happensDo this instead
Installing without the constraints fileDependency versions Airflow wasn't tested withUse --constraint with the URL from Step 2
Using Python 3.15The install stops: there's no constraints file for itUse Python 3.14
Forgetting export AIRFLOW_HOME="$PWD" in a new terminalAirflow uses ~/airflow, with another database and passwordExport it in every terminal for this project
Saving the Dag file outside dagsThe Dag never appearsSave it in dags/
Leaving out earthquake_count() at the endNo Dag is createdKeep the call
Committing before writing .gitignoreairflow.cfg and the password are in GitWrite .gitignore first

Troubleshooting​

SymptomLikely causeFix
command not found: airflowThe virtual environment isn't activesource .venv/bin/activate
The UI doesn't open on port 8085The [api] changes aren't saved, or Airflow isn't runningCheck with airflow config get-value api port
The run stays queuedThe Dag is pausedTrigger with Unpause selected, or switch on its toggle
The task fails with a network errorNo internet connection, or the USGS API didn't answer within 30 secondsCheck your connection and trigger it again

FAQ​

Do I need Docker?​

No. Everything runs from the project's virtual environment.

Why Python 3.14 and not 3.15?​

Airflow 3.4.0 supports Python 3.11 to 3.14, and its constraints files exist only for those.

Is airflow standalone for production?​

No, as its own output says. It's the quickest way to learn; a later part runs the parts separately, on PostgreSQL.

Why is the date in UTC?​

The USGS API works in UTC, and a pipeline that uses one time zone everywhere avoids days that are off by your local offset.

Conclusion​

You installed Apache Airflow® 3.4.0 on Python 3.14 with its constraints file, kept its files in the project with AIRFLOW_HOME, changed four settings, and started every part of Airflow with airflow standalone. Your first Dag, earthquake_count, asked the USGS API for yesterday's earthquakes, and its task log reported 338 for November 30, 2026. The project is in Git, without its secrets.

Part 2, coming next, splits the pipeline into several tasks that pass data to each other.

Additional Resources​

Earthquake data: Credit: U.S. Geological Survey.

Apache®, Apache Airflow and Airflow® are either registered trademarks or trademarks of The Apache Software Foundation in the United States and/or other countries. No endorsement by The Apache Software Foundation is implied by the use of these marks.