Absinthe: Schema, Resolvers & Mutations
Absinthe is the standard GraphQL toolkit for Elixir, most commonly paired with Phoenix -- Phoenix's plug pipeline handles routing to the GraphQL endpoint, and Phoenix Channels power Absinthe's real-time subscriptions.
Defining a Schema
defmodule MyAppWeb.Schema do
use Absinthe.Schema
object :user do
field :id, :id
field :name, :string
field :email, :string
end
query do
field :user, :user do
arg :id, non_null(:id)
resolve &Resolvers.User.find/3
end
end
endResolvers
defmodule Resolvers.User do
def find(_parent, %{id: id}, _context) do
case MyApp.Accounts.get_user(id) do
nil -> {:error, "User not found"}
user -> {:ok, user}
end
end
end
# A resolver fetches/computes the value for a specific field --
# returning {:error, ...} surfaces cleanly in GraphQL's errors arrayMutations
mutation do
field :create_user, :user do
arg :name, non_null(:string)
arg :email, non_null(:string)
resolve &Resolvers.User.create/3
end
end
# Mutations are for operations with side effects (create/update/delete),
# kept separate from read-only queries by GraphQL conventionContext: Request-Scoped Data
The context is populated per-request -- often with the current authenticated user from an auth plug -- and passed into every resolver, letting resolvers make authorization decisions without relying on global state.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free