This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Absinthe Cheat Sheet

A quick reference guide for Absinthe, the GraphQL implementation for Elixir and Phoenix, covering schemas, resolvers, types, and mutations.

· Published

Absinthe is the complete GraphQL toolkit for Elixir and Phoenix applications.

Getting Started

Core Concepts

  • Schema: The root definition of queries, mutations, subscriptions, and types.
  • Resolver: The Elixir function responsible for fetching or modifying data.
  • Type: Defines the structure, fields, and constraints of returned data entities.

Plug Integration

web/router.ex

defmodule Blog.Web.Router do
  use Phoenix.Router

  forward "/api", Absinthe.Plug,
    schema: Blog.Schema
end

Absinthe operates as a Plug that accepts your root schema configuration.

See: Absinthe Tutorial


Core Definitions

Schema Definition

web/schema.ex

defmodule Blog.Schema do
  use Absinthe.Schema
  import_types Blog.Schema.Types

  query do
    @desc "Get a list of blog posts"
    field :posts, list_of(:post) do
      resolve &Blog.PostResolver.all/2
    end
  end
end

This schema responds to { posts { ... } }, declares the return type as list_of(:post), and delegates execution to Blog.PostResolver.all/2.

Resolvers

web/resolvers/post_resolver.ex

defmodule Blog.PostResolver do
  def all(_args, _info) do
    {:ok, Blog.Repo.all(Blog.Post)}
  end
end

Resolvers return {:ok, result} or {:error, reason}.

Custom Types

web/schema/types.ex

defmodule Blog.Schema.Types do
  use Absinthe.Schema.Notation

  @desc "A blog post entity"
  object :post do
    field :id, :id
    field :title, :string
    field :body, :string
  end
end

Defines the :post object type for schema fields and resolvers.


Queries & Mutations

Query Arguments

GraphQL Query

{
  user(id: "1") {
    name
    email
  }
}

web/schema.ex

query do
  field :user, type: :user do
    arg :id, non_null(:id)
    resolve &Blog.UserResolver.find/2
  end
end

Resolver Implementation

def find(%{id: id} = _args, _info) do
  case Blog.Accounts.get_user(id) do
    nil -> {:error, "User not found"}
    user -> {:ok, user}
  end
end

Mutations

GraphQL Mutation

mutation CreatePost {
  post(title: "Hello World") {
    id
    title
  }
}

web/schema.ex

mutation do
  @desc "Create a new post"
  field :post, type: :post do
    arg :title, non_null(:string)
    resolve &Blog.PostResolver.create/2
  end
end

References

Related topics