Dagger SDKs
Dagger SDKs make it easy to call the Dagger API from your favorite programming language, by developing Dagger Functions or custom applications.
A Dagger SDK provides two components:
- A client library to call the Dagger API from your code
- Tooling to extend the Dagger API with your own Dagger Functions (bundled in a Dagger module)
The Dagger API uses GraphQL as its low-level language-agnostic framework, and can also be accessed using any standard GraphQL client. However, you do not need to know GraphQL to call the Dagger API; the translation to underlying GraphQL API calls is handled internally by the Dagger SDKs.
Stable Dagger SDKs are currently available for Go, TypeScript and Python. There are also experimental SDKs contributed by the community.
Dagger Functions
The recommended, and most common way, to interact with the Dagger API is through Dagger Functions. Dagger Functions are just regular code, written in your usual language using a type-safe Dagger SDK.
Dagger Functions are packaged, shared and reused using Dagger modules. A new Dagger module is initialized by calling dagger init
. This creates a new dagger.json
configuration file in the current working directory, together with sample Dagger Function source code. The configuration file will default the name of the module to the current directory name, unless an alternative is specified with the --name
argument.
Once a module is initialized, dagger develop --sdk=...
sets up or updates all the resources needed to develop the module locally using a Dagger SDK. By default, the module source code will be stored in the current working directory, unless an alternative is specified with the --source
argument.
Here is an example of initializing a Dagger module:
- Go
- Python
- TypeScript
dagger init --name=my-module
dagger develop --sdk=go
dagger init --name=my-module
dagger develop --sdk=python
dagger init --name=my-module
dagger develop --sdk=typescript
At any point, running dagger develop
regenerates the module's code based on dependencies and the current state of the module.
The default template from dagger develop
creates the following structure:
- Go
- Python
- TypeScript
.
├── LICENSE
├── dagger.gen.go
├── dagger.json
├── go.mod
├── go.sum
├── internal
│ ├── dagger
│ ├── querybuilder
│ └── telemetry
└── main.go
In this structure:
dagger.json
is the Dagger module configuration file.go.mod
/go.sum
manage the Go module and its dependencies.main.go
is where your Dagger module code goes. It contains sample code to help you get started.internal
contains automatically-generated types and helpers needed to configure and run the module:dagger
contains definitions for the Dagger API that's tied to the currently running Dagger Engine container.querybuilder
has utilities for building GraphQL queries (used internally by thedagger
package).telemetry
has utilities for sending Dagger Engine telemetry.
.
├── LICENSE
├── pyproject.toml
├── uv.lock
├── sdk
├── src
│ └── my_module
│ ├── __init__.py
│ └── main.py
└── dagger.json
In this structure:
dagger.json
is the Dagger module configuration file.pyproject.toml
manages the Python project configuration.uv.lock
manages the module's pinned dependencies.src/my_module/
is where your Dagger module code goes. It contains sample code to help you get started.sdk/
contains the vendored Python SDK client library.
This structure hosts a Python import package, with a name derived from the project name (in pyproject.toml
), inside a src
directory. This follows a Python convention that requires a project to be installed in order to run its code. This convention prevents accidental usage of development code since the Python interpreter includes the current working directory as the first item on the import path (more information is available in this blog post on Python packaging).
.
├── LICENSE
├── dagger.json
├── package.json
├── sdk
├── src
│ └── index.ts
├── tsconfig.json
└── yarn.lock
In this structure:
dagger.json
is the Dagger module configuration file.package.json
manages the module dependencies.src/
is where your Dagger module code goes. It contains sample code to help you get started.sdk/
contains the TypeScript SDK.
While you can use the utilities defined in the automatically-generated code above, you cannot edit these files. Even if you edit them locally, any changes will not be persisted when you run the module.
You can now write Dagger Functions using the selected Dagger SDK. Here is an example, which calls a remote API method and returns the result:
- Go
- Python
- TypeScript
package main
import (
"context"
)
type MyModule struct{}
func (m *MyModule) GetUser(ctx context.Context) (string, error) {
return dag.Container().
From("alpine:latest").
WithExec([]string{"apk", "add", "curl"}).
WithExec([]string{"apk", "add", "jq"}).
WithExec([]string{"sh", "-c", "curl https://randomuser.me/api/ | jq .results[0].name"}).
Stdout(ctx)
}
This Dagger Function includes the context as input and error as return in its signature.
from dagger import dag, function, object_type
@object_type
class MyModule:
@function
async def get_user(self) -> str:
return await (
dag.container()
.from_("alpine:latest")
.with_exec(["apk", "add", "curl"])
.with_exec(["apk", "add", "jq"])
.with_exec(
["sh", "-c", "curl https://randomuser.me/api/ | jq .results[0].name"]
)
.stdout()
)
Dagger Functions are implemented as @dagger.function decorated methods, of a @dagger.object_type decorated class.
It's possible for a module to implement multiple classes (object types), but the first one needs to have a name that matches the module's name, in PascalCase. This object is sometimes referred to as the main object.
For example, for a module initialized with dagger init --name=my-module
,
the main object needs to be named MyModule
.
import { dag, object, func } from "@dagger.io/dagger"
@object()
class MyModule {
@func()
async getUser(): Promise<string> {
return await dag
.container()
.from("alpine:latest")
.withExec(["apk", "add", "curl"])
.withExec(["apk", "add", "jq"])
.withExec([
"sh",
"-c",
"curl https://randomuser.me/api/ | jq .results[0].name",
])
.stdout()
}
}
You can try this Dagger Function by copying it into the default template generated by dagger init
, but remember that you must update the module name in the code samples above to match the name used when your module was first initialized.
In simple terms, this Dagger Function:
- initializes a new container from an
alpine
base image. - executes the
apk add ...
command in the container to add thecurl
andjq
utilities. - uses the
curl
utility to send an HTTP request to the URLhttps://randomuser.me/api/
and parses the response usingjq
. - retrieves and returns the output stream of the last executed command as a string.
Every Dagger Function has access to the dag
client, which is a pre-initialized Dagger API client. This client contains all the core types (like Container
, Directory
, etc.), as well as bindings to any dependencies your Dagger module has declared.
Here is an example call for this Dagger Function:
dagger call get-user
Here's what you should see:
{
"title": "Mrs",
"first": "Beatrice",
"last": "Lavigne"
}
Dagger Functions execute within containers spawned by the Dagger Engine. This "sandboxing" serves a few important purposes:
- Reproducibility: Executing in a well-defined and well-controlled container ensures that a Dagger Function runs the same way every time it is invoked. It also guards against creating "hidden dependencies" on ambient properties of the execution environment that could change at any moment.
- Caching: A reproducible containerized environment makes it possible to cache the result of Dagger Function execution, which in turn allows Dagger to automatically speed up operations.
- Security: Even when running third-party Dagger Functions sourced from a Git repository, those Dagger Functions will not have default access to your host environment (host files, directories, environment variables, etc.). Access to these host resources can only be granted by explicitly passing them as argument values to the Dagger Function.
Custom applications
An alternative approach is to develop a custom application using a Dagger SDK. This involves:
- installing the SDK for your selected language in your development environment
- initializing a Dagger API client in your application code
- calling and combining Dagger API methods from your application to achieve the required result
- executing your application using
dagger run
- Go
- Python
- TypeScript
The Dagger Go SDK requires Go 1.22 or later.
From an existing Go module, install the Dagger Go SDK using the commands below:
go get dagger.io/dagger@latest
After importing dagger.io/dagger
in your Go module code, run the following command to update go.sum
:
go mod tidy
This example demonstrates how to build a Go application for multiple architectures and Go versions using the Go SDK.
Clone an example project and create a new Go module in the project directory:
git clone https://go.googlesource.com/example
cd example/hello
mkdir multibuild && cd multibuild
go mod init multibuild
Create a new file in the multibuild
directory named main.go
and add the following code to it:
package main
import (
"context"
"fmt"
"dagger.io/dagger/dag"
)
func main() {
if err := build(context.Background()); err != nil {
fmt.Println(err)
}
}
func build(ctx context.Context) error {
fmt.Println("Building with Dagger")
// define build matrix
oses := []string{"linux", "darwin"}
arches := []string{"amd64", "arm64"}
goVersions := []string{"1.22", "1.23"}
defer dag.Close()
// get reference to the local project
src := dag.Host().Directory(".")
// create empty directory to put build outputs
outputs := dag.Directory()
for _, version := range goVersions {
// get `golang` image for specified Go version
imageTag := fmt.Sprintf("golang:%s", version)
golang := dag.Container().From(imageTag)
// mount cloned repository into `golang` image
golang = golang.WithDirectory("/src", src).WithWorkdir("/src")
for _, goos := range oses {
for _, goarch := range arches {
// create a directory for each os, arch and version
path := fmt.Sprintf("build/%s/%s/%s/", version, goos, goarch)
// set GOARCH and GOOS in the build environment
build := golang.WithEnvVariable("GOOS", goos)
build = build.WithEnvVariable("GOARCH", goarch)
// build application
build = build.WithExec([]string{"go", "build", "-o", path})
// get reference to build output directory in container
outputs = outputs.WithDirectory(path, build.Directory(path))
}
}
}
// write build artifacts to host
_, err := outputs.Export(ctx, ".")
if err != nil {
return err
}
return nil
}
This Go program imports the Dagger SDK and defines two functions. The build()
function represents the pipeline and creates a Dagger client, which provides an interface to the Dagger API. It also defines the build matrix, consisting of two OSs (darwin
and linux
) and two architectures (amd64
and arm64
), and builds the Go application for each combination. The Go build process is instructed via the GOOS
and GOARCH
build variables, which are reset for each case.
Try the Go program by executing the command below from the project directory:
dagger run go run multibuild/main.go
The dagger run
command executes the specified command in a Dagger session and displays live progress. The Go program builds the application for each OS/architecture combination and writes the build results to the host. You will see the build process run four times, once for each combination. Note that the builds are happening concurrently, because the builds do not depend on eachother.
Use the tree
command to see the build artifacts on the host, as shown below:
tree build
build
├── 1.22
│ ├── darwin
│ │ ├── amd64
│ │ │ └── hello
│ │ └── arm64
│ │ └── hello
│ └── linux
│ ├── amd64
│ │ └── hello
│ └── arm64
│ └── hello
└── 1.23
├── darwin
│ ├── amd64
│ │ └── hello
│ └── arm64
│ └── hello
└── linux
├── amd64
│ └── hello
└── arm64
└── hello
The Dagger Python SDK requires Python 3.10 or later.
Install the Dagger Python SDK in your project:
uv add dagger-io
If you prefer, you can alternatively add the Dagger Python SDK in your Python program. This is useful in case of dependency conflicts, or to keep your Dagger code self-contained.
uv add --script myscript.py dagger-io
This example demonstrates how to test a Python application against multiple Python versions using the Python SDK.
Clone an example project:
git clone --branch 0.101.0 https://github.com/tiangolo/fastapi
cd fastapi
Create a new file named test.py
in the project directory and add the following code to it.
"""Run tests for multiple Python versions concurrently."""
import sys
import anyio
import dagger
from dagger import dag
async def test():
versions = ["3.8", "3.9", "3.10", "3.11"]
async with dagger.connection(dagger.Config(log_output=sys.stderr)):
# get reference to the local project
src = dag.host().directory(".")
async def test_version(version: str):
python = (
dag.container()
.from_(f"python:{version}-slim-buster")
# mount cloned repository into image
.with_directory("/src", src)
# set current working directory for next commands
.with_workdir("/src")
# install test dependencies
.with_exec(["pip", "install", "-r", "requirements.txt"])
# run tests
.with_exec(["pytest", "tests"])
)
print(f"Starting tests for Python {version}")
# execute
await python.sync()
print(f"Tests for Python {version} succeeded!")
# when this block exits, all tasks will be awaited (i.e., executed)
async with anyio.create_task_group() as tg:
for version in versions:
tg.start_soon(test_version, version)
print("All tasks have finished")
anyio.run(test)
This Python program imports the Dagger SDK and defines an asynchronous function named test()
. This test()
function creates a Dagger client, which provides an interface to the Dagger API. It also defines the test matrix, consisting of Python versions 3.8
to 3.11
and iterates over this matrix, downloading a Python container image for each specified version and testing the source application in that version.
Add the dependency:
uv add --script test.py dagger-io
Run the Python program by executing the command below from the project directory:
dagger run uv run test.py
The dagger run
command executes the specified command in a Dagger session and displays live progress. The tool tests the application against each version concurrently and displays the following final output:
Starting tests for Python 3.8
Starting tests for Python 3.9
Starting tests for Python 3.10
Starting tests for Python 3.11
Tests for Python 3.8 succeeded!
Tests for Python 3.9 succeeded!
Tests for Python 3.11 succeeded!
Tests for Python 3.10 succeeded!
All tasks have finished
The Dagger TypeScript SDK requires TypeScript 5.0 or later. This SDK currently only supports Node.js (stable) and Bun (experimental). To execute the TypeScript program, you must also have an TypeScript executor like ts-node
or tsx
.
Install the Dagger TypeScript SDK in your project using npm
or yarn
:
// using npm
npm install @dagger.io/dagger@latest --save-dev
// using yarn
yarn add @dagger.io/dagger --dev
This example demonstrates how to test a Node.js application against multiple Node.js versions using the TypeScript SDK.
Create an example React project (or use an existing one) in TypeScript:
npx create-react-app my-app --template typescript
cd my-app
In the project directory, create a new file named build.mts
and add the following code to it:
import { dag } from '@dagger.io/dagger'
import * as dagger from '@dagger.io/dagger'
// initialize Dagger client
await dagger.connection(async () => {
// set Node versions against which to test and build
const nodeVersions = ["16", "18", "20"]
// get reference to the local project
const source = dag.host().directory(".", { exclude: ["node_modules/"] })
// for each Node version
for (const nodeVersion of nodeVersions) {
// get Node image
const node = dag.container().from(`node:${nodeVersion}`)
// mount cloned repository into Node image
const runner = node
.withDirectory("/src", source)
.withWorkdir("/src")
.withExec(["npm", "install"])
// run tests
await runner.withExec(["npm", "test", "--", "--watchAll=false"]).sync()
// build application using specified Node version
// write the build output to the host
await runner
.withExec(["npm", "run", "build"])
.directory("build/")
.export(`./build-node-${nodeVersion}`)
}
},
{ LogOutput: process.stderr }
)
This TypeScript program imports the Dagger SDK and defines an asynchronous function. This function creates a Dagger client, which provides an interface to the Dagger API. It also defines the test/build matrix, consisting of Node.js versions 16
, 18
and 20
, and iterates over this matrix, downloading a Node.js container image for each specified version and testing and building the source application against that version.
Run the program with a Typescript executor like ts-node
, as shown below:
dagger run node --loader ts-node/esm ./build.mts
The dagger run
command executes the specified command in a Dagger session and displays live progress. The program tests and builds the application against each version in sequence. At the end of the process, a built application is available for each Node.js version in a build-node-XX
folder in the project directory, as shown below:
tree -L 2 -d build-*
build-node-16
└── static
├── css
├── js
└── media
build-node-18
└── static
├── css
├── js
└── media
build-node-20
└── static
├── css
├── js
└── media
Differences
Here is a quick summary of differences between these two approaches.
Dagger Functions | Custom applications | |
---|---|---|
Pre-initialized Dagger API client | Y | N |
Direct host access | N | Y |
Direct third-party module access | Y | N |
Cross-language interoperability | Y | N |