Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 51

Building a Data Workflow with DAGs

This lesson is built with resources from airflow.apache.org and astronomer.io.

Hello! Welcome back to our module on Data Pipeline Orchestration.

In our last lesson, you learned to identify the conceptual building blocks of an Apache Airflow workflow: the DAG as the blueprint, Operators as the templates for work, and Tasks as the individual steps.

Today, we transition from theory to practice. Your goal is to create a simple Directed Acyclic Graph (DAG) to define a data workflow. We will walk through the process of writing the Python code for a complete, albeit simple, DAG file. As an architect, you're familiar with how configuration files and scripts define system behavior; a DAG file serves a similar purpose for data workflows.

1. The Structure of a DAG File

An Airflow DAG is defined in a Python script (.py file). This file doesn't execute the data processing itself. Instead, Airflow's scheduler parses this script to discover the DAG's structure, tasks, and schedule.

A basic DAG file consists of four main parts:

  1. Imports: Importing necessary classes like DAG, datetime, and the required Operators.
  2. DAG Instantiation: Creating an instance of the DAG class and defining its properties, such as its ID, schedule, and start date.
  3. Task Definitions: Creating task objects by instantiating Operator classes.
  4. Dependency Definitions: Specifying the order in which the tasks should run.

Let's build a simple DAG step-by-step. We will use the official Airflow documentation as our guide.

Airflow 101: Building Your First Workflow

The official Airflow documentation provides an excellent tutorial for creating your first workflow. We will use it to build our understanding piece by piece.

First, read the brief section titled 'Understanding the Dag Definition File'. This reinforces the idea that the Python script is a configuration file, a key concept for understanding how Airflow works.


2. Building a DAG, Step-by-Step

Let's construct a simple workflow that prints the date, waits for 5 seconds, and then runs a templated command.

Step 1: Imports

Every DAG file starts by importing the necessary components. For our simple DAG, we need:

  • DAG: The class used to instantiate a DAG object.
  • datetime: A standard Python library to specify dates, particularly the start_date.
  • BashOperator: The operator we'll use to define our tasks. It simply runs a bash command.
from __future__ import annotations

import pendulum

from airflow.models.dag import DAG
from airflow.operators.bash import BashOperator

(Note: Modern Airflow examples often use pendulum for robust timezone handling, but datetime is also common).

Step 2: DAG Instantiation

Next, you create the DAG object itself. This is typically done using a with statement, which provides a context for all tasks that belong to this DAG. You must provide a few key parameters:

  • dag_id: A unique string identifier for the DAG across your Airflow environment.
  • start_date: The date on which your DAG can begin to be scheduled.
  • schedule: Defines how often the DAG should run. Common values are '@daily', '@hourly', or a cron expression.
  • catchup: If set to False, the DAG will only run for the most recent schedule interval, preventing it from running for all past, un-triggered schedules between the start_date and the current date. This is often desirable during development.
with DAG(
    dag_id="my_first_dag",
    start_date=pendulum.datetime(2023, 1, 1, tz="UTC"),
    schedule="@daily",
    catchup=False,
    tags=["example"],
) as dag:
    # Tasks will be defined here

As a best practice, you can also define a default_args dictionary and pass it to the DAG. This allows you to set common properties (like retries or owner) for all tasks at once, a familiar pattern for promoting reusable and clean configuration.

Step 3: Task Definitions

Inside the with block, you define the tasks. A task is an instance of an Operator. You must give each task a unique task_id within the DAG.

Let's define two simple tasks using the BashOperator:

# The 'dag' object is implicitly passed to the operator
# because we are inside the 'with' block.

# Task 1: prints the current date
task1 = BashOperator(
    task_id="print_date",
    bash_command="date",
)

# Task 2: sleeps for 5 seconds
task2 = BashOperator(
    task_id="sleep",
    bash_command="sleep 5",
    retries=3, # We can override default_args on a per-task basis
)

Step 4: Setting Dependencies

Finally, you define the relationships between the tasks. This is what turns your list of tasks into a graph. The most common way to do this is with the bitshift operators >> (downstream) and << (upstream).

If we want task2 to run only after task1 has completed successfully, we write:

task1 >> task2

This single line establishes the directed edge in our graph: task1 -> task2.

Example of a Simple Directed Acyclic Graph (DAG)
This image shows a more complex graph, but the principle is the same. The arrows represent the dependencies you define in your code, like `runme_0 >> run_after_loop`.

3. Putting It All Together

Here is the complete, minimal DAG file incorporating all the steps above.

from __future__ import annotations

import pendulum

from airflow.models.dag import DAG
from airflow.operators.bash import BashOperator

# 1. DAG Instantiation
with DAG(
    dag_id="my_first_dag",
    start_date=pendulum.datetime(2023, 1, 1, tz="UTC"),
    schedule="@daily",
    catchup=False,
    tags=["example"],
) as dag:
    # 2. Task Definitions
    task1 = BashOperator(
        task_id="print_date",
        bash_command="date",
    )

    task2 = BashOperator(
        task_id="sleep",
        bash_command="sleep 5",
        retries=3,
    )

    # 3. Dependency Definition
    task1 >> task2

This simple script is a complete and valid DAG file that Airflow can parse and schedule.

To deepen your understanding, let's review a comprehensive resource that breaks down these components and shows two different syntaxes for writing DAGs.

Introduction to Apache Airflow® DAGs

The Astronomer documentation provides a fantastic comparison of the two main ways to write a DAG: the traditional syntax we just used, and the more modern TaskFlow API. Recognizing both is crucial.

Please read the sections 'Write a DAG' and 'DAG-level parameters'. Focus on the side-by-side comparison of the 'Taskflow' and 'Traditional' syntax examples. This will connect back to what we discussed in the last lesson.

As you saw in the reading, the TaskFlow API uses Python decorators (@dag and @task) to create a more concise and Python-native authoring experience, especially when your tasks involve running Python code. The Traditional syntax, which we used above, is powerful for its explicit instantiation of any operator type and is very common in existing codebases.

Test your understanding!

You need to create a simple workflow to prepare a daily report. The steps are:

  1. Fetch data (fetch_data task).
  2. After fetching is done, generate the report (generate_report task).
  3. After the report is generated, send a notification (send_notification task).

Using the traditional syntax we learned today, write the Python code snippet that defines these three tasks and their dependencies. Assume the tasks are BashOperator instances and that they are inside a with DAG(...) as dag: block.

Show answer
# Task Definitions
fetch_data = BashOperator(
    task_id="fetch_data",
    bash_command="echo 'Fetching data...'",
)

generate_report = BashOperator(
    task_id="generate_report",
    bash_command="echo 'Generating report...'",
)

send_notification = BashOperator(
    task_id="send_notification",
    bash_command="echo 'Sending notification...'",
)

# Dependency Definition
fetch_data >> generate_report >> send_notification

This code creates a simple, linear chain of dependencies, ensuring the tasks execute in the correct order.


Conclusion

Congratulations! you have now walked through the fundamental steps of authoring an Airflow DAG. You can now read and write a basic Python script that defines a complete data workflow.

Key Takeaways:

  • A DAG file is a Python script that defines a workflow's structure through imports, DAG instantiation, task definitions, and dependency setting.
  • The with DAG(...) as dag: block provides the context for defining a workflow.
  • Tasks are instances of Operator classes (e.g., BashOperator) and must have a unique task_id.
  • Dependencies are set using bitshift operators (>>, <<) to define the execution order and create the "graph".
  • Both Traditional and TaskFlow API syntaxes are valid ways to define DAGs.

In our next lesson, we will build upon this foundation to implement more complex dependencies between tasks, exploring how to create parallel paths, branches, and joins in your workflows.