Skip to main content

Apache Airflow® Tutorial for Data Pipelines in Python — Part 2: Tasks, Operators and Dependencies

· 29 min read
Jagdish Kumawat
Founder @ Dewiride

In Part 1, one task did all the work. A real pipeline splits the work into steps that each do one thing, so you can see what every step did and run again only the step that failed. In Part 2 you turn the earthquake pipeline into four tasks that hand data to each other, and learn the three ideas that make it work: tasks, operators and dependencies.

This is Part 2 of the series.

  1. Part 1: Install Airflow and Run Your First Dag
  2. Part 2: Tasks, Operators and Dependencies (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 This Part​

  • A Dag called earthquake_pipeline with four tasks: extract, transform, load and archive_raw_file.
  • A CSV file, data/earthquakes.csv, with one row for every earthquake USGS recorded yesterday (UTC): its ID, time, magnitude, place, latitude, longitude and depth.

Tasks, Operators and Dependencies​

Airflow's documentation defines these words like this.

A task is one step of a pipeline: "A Task is the basic unit of execution in Airflow." Each task runs on its own, with its own state, such as running, success or failed, and its own log.

An operator is a ready-made kind of task. The documentation calls operators "predefined task templates": BashOperator runs a shell command, for example, and you only fill in which command. A TaskFlow @task, which Part 1 used, is "a custom Python function packaged up as a Task". Under the hood, both are built on the same Airflow class, BaseOperator, so Airflow handles them the same way.

A dependency says which task waits for which. By default, "a Task will run when all of its upstream (parent) tasks have succeeded". Upstream tasks are the ones a task waits for.

An XCom carries a value from one task to another. Tasks "don't pass information to each other by default, and run entirely independently", so Airflow stores what a task returns in its database as an XCom, short for "cross-communications", and gives it to the tasks that ask for it. XComs are for small values: the documentation says they "are only designed for small amounts of data; do not use them to pass around large values, like dataframes". So the pipeline below keeps the earthquakes in files, and passes only the day and file paths.

The Example: Four Tasks for Yesterday's Earthquakes​

Part 1's Dag asked USGS only how many earthquakes happened yesterday. This part's Dag fetches the earthquakes themselves and keeps them in a CSV file, in four tasks:

TaskKindWhat it doesWhat it hands on
extract@taskAsks the USGS API for yesterday's earthquakes and saves the answer as a fileThe day, and the file's path
transform@taskTurns every earthquake in that file into one row of a new CSV fileThe CSV file's path
load@taskAdds the day's rows to data/earthquakes.csv, replacing the day's earlier rowsThe number of rows
archive_raw_fileBashOperatorCompresses the saved answer with gzipNothing

The solid arrows carry values, as XComs. The dotted arrow carries none: archive_raw_file only has to wait for transform, because transform reads the file that gzip replaces.

What This Part Costs​

Nothing. Everything runs on your computer, and the USGS API is free and needs no key.

Prerequisites​

Step 1: Start Airflow​

Open a terminal in the dewiride-earthquake-pipeline folder and start Airflow the way Part 1 ended:

Terminal
source .venv/bin/activate
export AIRFLOW_HOME="$PWD"
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)
standalone | Password for the admin user has been previously generated in /Users/you/source/dewiride-earthquake-pipeline/simple_auth_manager_passwords.json.generated. Not echoing it here.
standalone | Checking database is initialized
...
standalone | Database ready
...
api-server | 2026-12-04T10:08:21.985423Z [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 password note pointing to the file made on the first start, Database ready, the API server running on http://127.0.0.1:8085, and Airflow is ready.

  • source .venv/bin/activate turns on the project's virtual environment, and export AIRFLOW_HOME="$PWD" tells Airflow that its files are in this folder.
  • airflow standalone starts every part of Airflow. This time it doesn't print the password: it made it on the first start, and names the file that holds it. How to Find the Admin Password for Apache Airflow® standalone shows how to read it.

The FileType is deprecated warnings that Airflow prints before these lines are left out, as in Part 1. Fixed: "FileType is deprecated. Simply open files after parsing arguments." explains them.

Leave this terminal running. Open http://127.0.0.1:8085 and sign in as admin.

Step 2: Write the Pipeline Dag​

Create the file dags/earthquake_pipeline.py. Here it is piece by piece, and then whole.

The imports and settings​

dags/earthquake_pipeline.py
"""Extract, transform and load yesterday's earthquakes from the USGS API."""

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

from airflow.providers.standard.operators.bash import BashOperator
from airflow.sdk import dag, task

USGS_QUERY_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query"
DATA_DIR = Path(__file__).resolve().parent.parent / "data"
COLUMNS = ["id", "time", "magnitude", "place", "latitude", "longitude", "depth_km"]

log = logging.getLogger(__name__)
  • csv, json, logging, datetime, pathlib and urllib come with Python, so there's nothing to install.
  • BashOperator comes from Airflow's standard provider, apache-airflow-providers-standard. The install in Part 1 included it, at version 1.21.0.
  • dag and task are the TaskFlow decorators from Part 1.
  • USGS_QUERY_URL is the USGS API's query method, which answers with the earthquakes themselves. Part 1 used its count method. How to Query the USGS Earthquake API with curl shows both.
  • DATA_DIR is the data folder of the project. Path(__file__) is this file, its .parent is dags, and the next .parent is the project folder. Every file the pipeline writes goes under data.
  • COLUMNS lists the CSV file's columns, in order.

Two helper functions​

dags/earthquake_pipeline.py
def to_row(feature: dict) -> dict:
"""Turn one earthquake from the USGS answer into one row of the CSV file."""
properties = feature["properties"]
longitude, latitude, depth_km = feature["geometry"]["coordinates"]
return {
"id": feature["id"],
"time": datetime.fromtimestamp(properties["time"] / 1000, tz=UTC).isoformat(),
"magnitude": properties["mag"],
"place": properties["place"],
"latitude": latitude,
"longitude": longitude,
"depth_km": depth_km,
}


def write_csv(path: Path, rows: list[dict]) -> None:
"""Write the rows under a header, replacing the file only once it is complete."""
temporary = path.with_name(path.name + ".tmp")
with temporary.open("w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=COLUMNS)
writer.writeheader()
writer.writerows(rows)
temporary.replace(path)

These are plain Python functions, not tasks: the tasks call them.

  • The USGS answer is GeoJSON: a list of features, one per earthquake, each with its properties (time, magnitude, place) and its geometry. USGS's GeoJSON format page lists the three coordinates as longitude, latitude and depth, in that order. Its Event Terms page says that times are in "milliseconds since the epoch" and the depth is "in kilometers". So to_row divides the time by 1000, to get seconds, and turns it into a UTC date and time.
  • write_csv writes the rows to a temporary file next to the real one, such as earthquakes.csv.tmp, and then replace() puts that file in place of the real one in a single step. If a task fails halfway through writing, only the temporary file is half written, and the real file stays as it was.

The Dag and the extract task​

dags/earthquake_pipeline.py
@dag(schedule=None, tags=["earthquakes"])
def earthquake_pipeline():
"""Load yesterday's earthquakes (UTC) into data/earthquakes.csv."""

@task(multiple_outputs=True)
def extract() -> dict[str, str]:
today = datetime.now(UTC).date()
day = today - timedelta(days=1)
query = urlencode(
{
"format": "geojson",
"eventtype": "earthquake",
"starttime": day.isoformat(),
"endtime": today.isoformat(),
}
)
raw_file = DATA_DIR / "raw" / f"earthquakes-{day}.geojson"
raw_file.parent.mkdir(parents=True, exist_ok=True)
with urlopen(f"{USGS_QUERY_URL}?{query}", timeout=60) as response:
raw_file.write_bytes(response.read())
log.info("Saved the USGS answer for %s to %s.", day, raw_file)
return {"day": day.isoformat(), "raw_file": str(raw_file)}
  • schedule=None means the Dag runs only when you trigger it, as in Part 1. Part 3 gives it a schedule.
  • extract asks USGS for every earthquake from the start of yesterday to the start of today, in UTC, as GeoJSON. It saves the answer as it came, in data/raw/earthquakes-<day>.geojson, and logs where it saved it.
  • The request to USGS sits inside the task, not at the top of the file. Airflow's best practices say that a Dag file's top-level code "should not run any database access, heavy computations and networking operations." The Dag processor runs that code every time it reads the file; code inside a task runs only when the task runs.
  • The task returns two values, the day and the file's path, as text in a dictionary. multiple_outputs=True makes Airflow store each key as its own XCom, so other tasks can take only the value they need, as extracted["day"] or extracted["raw_file"]. With the -> dict[str, str] return type, Airflow would split the dictionary even without it; writing it out makes that visible. How to Return Several Values from a Task with multiple_outputs in Apache Airflow® shows both.

The transform and load tasks​

dags/earthquake_pipeline.py
@task
def transform(day: str, raw_file: str) -> str:
with open(raw_file, encoding="utf-8") as file:
features = json.load(file)["features"]
rows = [to_row(feature) for feature in features]
processed_file = DATA_DIR / "processed" / f"earthquakes-{day}.csv"
processed_file.parent.mkdir(parents=True, exist_ok=True)
write_csv(processed_file, rows)
log.info("Wrote %d earthquakes for %s to %s.", len(rows), day, processed_file)
return str(processed_file)

@task
def load(day: str, processed_file: str) -> int:
with open(processed_file, newline="", encoding="utf-8") as file:
new_rows = list(csv.DictReader(file))
target = DATA_DIR / "earthquakes.csv"
kept_rows = []
if target.exists():
with open(target, newline="", encoding="utf-8") as file:
kept_rows = [
row for row in csv.DictReader(file) if row["time"][:10] != day
]
rows = sorted(kept_rows + new_rows, key=lambda row: row["time"])
write_csv(target, rows)
log.info("Loaded %d earthquakes for %s into %s.", len(new_rows), day, target)
return len(new_rows)
  • transform reads the saved answer, turns each earthquake into a row with to_row, writes the rows to data/processed/earthquakes-<day>.csv and returns that file's path.
  • load reads those rows, and the current data/earthquakes.csv if there is one. It keeps every row from other days, leaves out this day's rows (the first 10 characters of time are the date, as in 2026-12-03), adds the new rows, sorts them all by time and writes the file. It returns how many rows it loaded.
  • Because load replaces the day's rows instead of adding to them, loading the same day twice doesn't count any earthquake twice. Re-running past days, later in the series, depends on this.

Connect the tasks​

dags/earthquake_pipeline.py
extracted = extract()
processed = transform(extracted["day"], extracted["raw_file"])
load(extracted["day"], processed)

archive_raw_file = BashOperator(
task_id="archive_raw_file",
bash_command='gzip --force --verbose "$RAW_FILE"',
env={"RAW_FILE": extracted["raw_file"]},
append_env=True,
do_xcom_push=False,
)
processed >> archive_raw_file


earthquake_pipeline()

The end of the earthquake_pipeline.py Dag file in an editor window: extract, transform and load connected by passing results, the archive_raw_file BashOperator that runs gzip on RAW_FILE from env, and processed >> archive_raw_file.

These lines turn the functions into tasks and set the order they run in:

  • Calling extract() here doesn't run it. The TaskFlow documentation explains that "rather than executing it, you will get an object representing the XCom for the result". So extracted stands for the value extract will return when it runs.
  • Passing extracted["day"] and extracted["raw_file"] to transform does two things. When the Dag runs, Airflow hands those two XComs to transform. And transform waits for extract, without you writing that order anywhere.
  • load(extracted["day"], processed) uses the results of both tasks, so load waits for both.
  • archive_raw_file is a classic operator: instead of decorating a function, you create a BashOperator and fill in its arguments. task_id names the task, and bash_command is the command bash runs. gzip compresses the file and replaces it with a .gz file. --force lets it replace a .gz file left by an earlier run for the same day, instead of asking, and --verbose makes it print how much smaller the file got. How to Run a Bash Command in Apache Airflow® with BashOperator covers the operator.
  • env={"RAW_FILE": extracted["raw_file"]} hands extract's result to the command as an environment variable, and makes archive_raw_file wait for extract. env is one of the arguments Airflow fills in when the task runs (How to Pass a TaskFlow Result to a Classic Operator in Apache Airflow®). The command reads the path as "$RAW_FILE", in double quotes. The BashOperator guide warns that Airflow doesn't escape values written into the command itself, and says to "pass this via the env kwarg and use double-quotes inside the Bash command".
  • append_env=True keeps the rest of the environment, such as PATH. Without it, the variables in env "are used instead of inheriting the current process environment" (How to Set Environment Variables for BashOperator in Apache Airflow® with env and append_env). In Airflow 3.4.0 on macOS, env without append_env=True also makes bash run your ~/.bashrc before the command, so anything that file prints shows up in the task's log. Fixed: BashOperator Runs ~/.bashrc When env Is Set in Apache Airflow® explains why.
  • do_xcom_push=False stops the task from storing an XCom. By default, BashOperator stores the last line of the command's output as one. No task needs what gzip prints, so it stays out of Airflow's database (How to Stop a Task from Pushing an XCom in Apache Airflow® with do_xcom_push=False).
  • processed >> archive_raw_file makes archive_raw_file wait for transform too. No value passes between them, so nothing else links them: >>, a bitshift operator, sets the order on its own. The documentation recommends it, "as they are easier to read in most cases" (How to Set Task Dependencies with Bitshift Operators (>> and <<) in Apache Airflow®). Without this line, gzip could replace the raw file before transform has read it.
  • earthquake_pipeline() at the bottom creates the Dag, as in Part 1.

The complete file​

dags/earthquake_pipeline.py
"""Extract, transform and load yesterday's earthquakes from the USGS API."""

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

from airflow.providers.standard.operators.bash import BashOperator
from airflow.sdk import dag, task

USGS_QUERY_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query"
DATA_DIR = Path(__file__).resolve().parent.parent / "data"
COLUMNS = ["id", "time", "magnitude", "place", "latitude", "longitude", "depth_km"]

log = logging.getLogger(__name__)


def to_row(feature: dict) -> dict:
"""Turn one earthquake from the USGS answer into one row of the CSV file."""
properties = feature["properties"]
longitude, latitude, depth_km = feature["geometry"]["coordinates"]
return {
"id": feature["id"],
"time": datetime.fromtimestamp(properties["time"] / 1000, tz=UTC).isoformat(),
"magnitude": properties["mag"],
"place": properties["place"],
"latitude": latitude,
"longitude": longitude,
"depth_km": depth_km,
}


def write_csv(path: Path, rows: list[dict]) -> None:
"""Write the rows under a header, replacing the file only once it is complete."""
temporary = path.with_name(path.name + ".tmp")
with temporary.open("w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=COLUMNS)
writer.writeheader()
writer.writerows(rows)
temporary.replace(path)


@dag(schedule=None, tags=["earthquakes"])
def earthquake_pipeline():
"""Load yesterday's earthquakes (UTC) into data/earthquakes.csv."""

@task(multiple_outputs=True)
def extract() -> dict[str, str]:
today = datetime.now(UTC).date()
day = today - timedelta(days=1)
query = urlencode(
{
"format": "geojson",
"eventtype": "earthquake",
"starttime": day.isoformat(),
"endtime": today.isoformat(),
}
)
raw_file = DATA_DIR / "raw" / f"earthquakes-{day}.geojson"
raw_file.parent.mkdir(parents=True, exist_ok=True)
with urlopen(f"{USGS_QUERY_URL}?{query}", timeout=60) as response:
raw_file.write_bytes(response.read())
log.info("Saved the USGS answer for %s to %s.", day, raw_file)
return {"day": day.isoformat(), "raw_file": str(raw_file)}

@task
def transform(day: str, raw_file: str) -> str:
with open(raw_file, encoding="utf-8") as file:
features = json.load(file)["features"]
rows = [to_row(feature) for feature in features]
processed_file = DATA_DIR / "processed" / f"earthquakes-{day}.csv"
processed_file.parent.mkdir(parents=True, exist_ok=True)
write_csv(processed_file, rows)
log.info("Wrote %d earthquakes for %s to %s.", len(rows), day, processed_file)
return str(processed_file)

@task
def load(day: str, processed_file: str) -> int:
with open(processed_file, newline="", encoding="utf-8") as file:
new_rows = list(csv.DictReader(file))
target = DATA_DIR / "earthquakes.csv"
kept_rows = []
if target.exists():
with open(target, newline="", encoding="utf-8") as file:
kept_rows = [
row for row in csv.DictReader(file) if row["time"][:10] != day
]
rows = sorted(kept_rows + new_rows, key=lambda row: row["time"])
write_csv(target, rows)
log.info("Loaded %d earthquakes for %s into %s.", len(new_rows), day, target)
return len(new_rows)

extracted = extract()
processed = transform(extracted["day"], extracted["raw_file"])
load(extracted["day"], processed)

archive_raw_file = BashOperator(
task_id="archive_raw_file",
bash_command='gzip --force --verbose "$RAW_FILE"',
env={"RAW_FILE": extracted["raw_file"]},
append_env=True,
do_xcom_push=False,
)
processed >> archive_raw_file


earthquake_pipeline()

Save the file. In the airflow standalone terminal, the Dag processor finds it within seconds:

Output (excerpt)
dag-processor | 2026-12-04T10:08:40.998709Z [info ] Found 2 files for bundle dags-folder (dag_discovery_safe_mode=True) [airflow.dag_processing.manager.DagFileProcessorManager] loc=manager.py:1033
dag-processor | 2026-12-04T10:08:42.292584Z [info ] Creating ORM DAG for earthquake_pipeline [airflow.dag_processing.collection] loc=collection.py:104

The two files are Part 1's earthquake_count.py and the new one. Creating ORM DAG for earthquake_pipeline means Airflow stored the new Dag in its database.

Step 3: Remove Part 1's Dag​

earthquake_pipeline does everything earthquake_count did, and more, so remove the old file. Open a second terminal in the project folder:

Terminal
rm dags/earthquake_count.py
ls dags
Output
earthquake_pipeline.py

The terminal after rm dags/earthquake_count.py and ls dags: only earthquake_pipeline.py is left in the dags folder.

rm deletes the file, and ls dags lists what's left in the folder: only the new Dag. Within seconds, the Dag processor reports Found 1 files, and the Dags page in the UI lists one Dag:

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

earthquake_pipeline is paused, like every new Dag. Removing the file took earthquake_count off the list, but Airflow keeps its run in the database. How to Delete a Dag and Its History in Apache Airflow® shows how to remove that too.

Step 4: See the Dependencies in the Graph​

Click earthquake_pipeline to open it, then click Show Graph, the icon with three joined boxes at the top left:

The Graph view of earthquake_pipeline: extract on the left, connected to transform, load and archive_raw_file; transform connected to load and archive_raw_file. Each box shows @task or BashOperator under the task's name.

Each box is a task, with its kind under its name: @task or BashOperator. Each line is a dependency; read them from left to right. extract has three lines going out, because three tasks use its results. load and archive_raw_file both wait for transform, but not for each other, so Airflow can run them at the same time. How to Use the Graph View in Apache Airflow® explains the rest of the view.

Step 5: Run the Pipeline​

Click Trigger at the top right of the page:

The Trigger Dag - earthquake_pipeline 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. As in Part 1, this starts one run and unpauses the Dag. When the run ends, the grid on the left shows all four tasks in green:

The earthquake_pipeline Dag page: Latest Run 2026-12-04 10:10:12 with a green check, the toggle on, and extract, transform, archive_raw_file and load all green in the grid.

The whole run took about 10 seconds. Each task's page, which the next step opens, shows when the task ran:

TaskStartedEnded
extract10:10:1410:10:19
transform10:10:1910:10:21
load10:10:2110:10:23
archive_raw_file10:10:2110:10:23

The times are UTC, on December 4, 2026. Each task started when the tasks it waits for had finished, and load and archive_raw_file ran at the same time, as the graph allowed.

Step 6: Follow the Data from Task to Task​

Click the green square of extract in the grid. Its Logs tab shows the task's two log lines. I turned on line wrapping so the long lines fit (How to Wrap Long Lines in a Task Log in the Apache Airflow® UI):

The log of the extract task: Success in 4.32 seconds, the line Saved the USGS answer for 2026-12-03 to the raw GeoJSON file, and Done. Returned value was a dictionary with day and raw_file.

Saved the USGS answer for 2026-12-03 … is the task's log.info line, and Done. Returned value was: {'day': '2026-12-03', 'raw_file': '…'} is the dictionary it returned.

The task's XCom tab lists what Airflow stored. Here it is in the graph view, where clicking a task opens the same tabs, as icons, next to the graph:

The graph view with every task green and extract selected; its XCom tab lists 3 XCom entries: day 2026-12-03, raw_file with the path of the GeoJSON file, and return_value.

extract stored three XComs: day and raw_file, one for each key of its dictionary, and return_value, the whole dictionary. transform, load and archive_raw_file took their values from here. How to See a Task's XComs in the Apache Airflow® UI shows the tab in detail.

Open transform and load the same way. Their logs show what they did with those values:

The log of the transform task: Wrote 296 earthquakes for 2026-12-03 to the processed CSV file, and Done. Returned value was the file's path.

The log of the load task: Loaded 296 earthquakes for 2026-12-03 into data/earthquakes.csv, and Done. Returned value was: 296.

transform wrote 296 earthquakes for December 3 to the processed file and returned its path. load put the same 296 into data/earthquakes.csv and returned 296. USGS keeps reviewing its catalog, so the same day can give a slightly different count later.

Then open archive_raw_file:

The log of the archive_raw_file task: Running command with gzip --force --verbose "$RAW_FILE", the output showing the GeoJSON file 87.4% smaller and replaced with a .gz file, and Command exited with return code 0.

  • Tmp dir root location is where BashOperator makes the temporary folder it runs the command in.
  • Running command shows the command with $RAW_FILE still in it: Airflow handed bash the path through the environment, and bash filled it in.
  • The output is gzip's: the file got 87.4% smaller and was replaced with earthquakes-2026-12-03.geojson.gz.
  • Command exited with return code 0 means the command worked.

This task stored no XCom, because of do_xcom_push=False. Its Rendered Templates tab shows its arguments as Airflow filled them in for this run:

The Rendered Templates tab of archive_raw_file: bash_command is gzip --force --verbose "$RAW_FILE", and env holds RAW_FILE set to the path of the 2026-12-03 GeoJSON file.

env holds the real path that extract returned. How to See a Task's Rendered Templates in the Apache Airflow® UI explains the tab. When a classic operator gets a wrong value, this tab is the first place to look.

Step 7: Check the Files​

In the second terminal, look at what the run wrote:

Terminal
ls -R data
Output
earthquakes.csv processed raw

data/processed:
earthquakes-2026-12-03.csv

data/raw:
earthquakes-2026-12-03.geojson.gz

ls -R lists a folder and every folder inside it. data holds earthquakes.csv and two folders: processed, with the day's CSV file, and raw, with the compressed USGS answer.

Terminal
head -n 4 data/earthquakes.csv
Output
id,time,magnitude,place,latitude,longitude,depth_km
hv75079487,2026-12-03T00:01:16.440000+00:00,2.2,"2 km SW of Pāhala, Hawaii",19.1916675567627,-155.496002197266,35.2400016784668
aka2026xwpnla,2026-12-03T00:05:09.955000+00:00,2,"96 km ESE of McCarthy, Alaska",61.115,-141.244,8.6
us6000uf88,2026-12-03T00:11:04.974000+00:00,3.7,"91 km SW of Atka, Alaska",51.6077,-175.1327,33.207

head -n 4 prints the first four lines of the file: the header, then the first three earthquakes of December 3, UTC. The first one, of magnitude 2.2, was 2 km southwest of Pāhala, Hawaii, 35 km deep. Its longitude is negative because it's in the west: USGS's Event Terms page gives "Negative values for western longitudes". The place has a comma in it, so the CSV writer put it in double quotes.

Terminal
wc -l data/earthquakes.csv
Output
297 data/earthquakes.csv

wc -l counts the file's lines: 297, the header plus the 296 earthquakes that load reported.

The terminal after ls -R data, head -n 4 data/earthquakes.csv and wc -l data/earthquakes.csv: the data folder with earthquakes.csv, processed and raw, the CSV header and three earthquakes, and 297 lines.

Step 8: Put the Pipeline in Git​

The data folder holds what the pipeline makes, not code, so keep it out of Git. Add these lines at the end of .gitignore, after a blank line:

.gitignore
# The files the pipeline writes
data/

Then see what changed since Part 1's commit:

Terminal
git status --short
Output
M .gitignore
D dags/earthquake_count.py
?? dags/earthquake_pipeline.py

M is a changed file, D a deleted one, and ?? a new one that Git doesn't track yet. data/ isn't listed, because Git ignores it now. Commit the three changes:

Terminal
git add .
git commit -m "Extract, transform and load yesterday's earthquakes into a CSV file"
Output
[main c2ff659] Extract, transform and load yesterday's earthquakes into a CSV file
3 files changed, 113 insertions(+), 40 deletions(-)
delete mode 100644 dags/earthquake_count.py
create mode 100644 dags/earthquake_pipeline.py

The terminal after git status --short, with .gitignore changed, earthquake_count.py deleted and earthquake_pipeline.py new, then the commit with 3 files changed.

The commit holds the new Dag, the removed one and the new .gitignore lines. Your commit ID will be different from c2ff659.

Your Project Now Looks Like This​

dewiride-earthquake-pipeline
dewiride-earthquake-pipeline/
├── .git/
├── .gitignore
├── .venv/
├── airflow.cfg
├── airflow.db
├── dags/
│ └── earthquake_pipeline.py
├── data/
│ ├── earthquakes.csv
│ ├── processed/
│ │ └── earthquakes-2026-12-03.csv
│ └── raw/
│ └── earthquakes-2026-12-03.geojson.gz
├── 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. If it stays at Shutting down components and the prompt doesn't come back, Fixed: airflow standalone Hangs at "Shutting down components" After Ctrl+C shows how to end it. To start again later, run the three commands from Step 1 in the project folder.

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

Common Mistakes​

MistakeWhat happensDo this instead
Passing the earthquakes themselves from task to taskThey're stored in Airflow's database as XComs, which are meant for small valuesSave them in a file and pass the file's path
Calling the USGS API at the top of the Dag fileThe request runs every time the Dag processor reads the fileMake the request inside a task
Misspelling a key, such as extracted["raw_fle"]Nothing fails at that point: the next task gets NoneUse the keys extract returns, exactly as written
Leaving out processed >> archive_raw_filegzip can replace the raw file before transform reads itKeep the line
Writing the path into bash_command itselfAirflow puts it in as it is, without escapingPass it in env and write "$RAW_FILE", in double quotes
Leaving out append_env=TrueThe command gets only RAW_FILE and bash's default PATH, and on macOS bash runs your ~/.bashrc firstKeep append_env=True
Leaving data/ out of .gitignoreThe pipeline's output goes into Git with the codeAdd data/

Troubleshooting​

SymptomLikely causeFix
earthquake_count is still on the Dags pageIts file is still in dagsDelete it as in Step 3
extract fails with a network errorNo internet connection, or USGS didn't answer within 60 secondsCheck your connection and trigger the Dag again
Lines from your ~/.bashrc appear in the archive_raw_file logappend_env=True is missing, so bash ran ~/.bashrcKeep append_env=True, and see Fixed: BashOperator Runs ~/.bashrc When env Is Set in Apache Airflow®
Ctrl+C stops at Shutting down components, and the prompt doesn't come backA known problem in Airflow 3.4.0See Fixed: airflow standalone Hangs at "Shutting down components" After Ctrl+C

FAQ​

Why does the pipeline pass file paths instead of the data?​

Because XComs are kept in Airflow's database. The documentation says the default backend "stores XComs in the Airflow database, which works well for small values but can cause issues with large values or a high volume of XComs." A file's path stays small, however many earthquakes the file holds.

Can TaskFlow tasks and classic operators be in the same Dag?​

Yes. archive_raw_file is a BashOperator in a Dag of @task functions, and it takes extract's result through env. To Airflow, both are tasks.

Why did load and archive_raw_file run at the same time?​

Neither waits for the other. A task runs once all of its upstream tasks have succeeded, and for both of them that happened at 10:10:21.

What happens if I run the Dag twice in one day?​

Both runs load the same day, yesterday. extract saves the answer again, load replaces the day's rows instead of adding them a second time, and gzip --force replaces the earlier .gz file.

Conclusion​

You split the pipeline into four tasks. extract, transform and load are TaskFlow tasks that hand each other the day and the files' paths as XComs, and archive_raw_file is a BashOperator that gets its file through env. Passing results set most of the order for you, and >> added the one dependency that carries no value. The run turned USGS's answer for December 3, 2026 into 296 rows in data/earthquakes.csv, and the project is in Git.

Part 3, coming next, puts the pipeline on a schedule, so that each run loads its own day without a click.

Additional Resources​

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


← Previous: Part 1: Install Airflow and Run Your First Dag

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.