This Absinthe Cheat Sheet offers a concise overview of essential concepts and components for building GraphQL APIs in Elixir. It covers the fundamental building blocks such as Schema, Resolver, and Type, demonstrating how they interact within the Phoenix framework to define and resolve GraphQL queries. The cheat sheet includes code snippets for router configuration, schema definition, resolver functions, and type specification, making it a practical guide for developers working with Absinthe and GraphQL in Elixir projects.
Introduction
Concepts
Schema
- The root. Defines what queries you can do, and what types they return.Resolver
- Functions that return data.Type
- A type definition describing the shape of the data you'll return.
Plug
web/router.ex
defmodule Blog.Web.Router do
use Phoenix.Router
forward "/", Absinthe.Plug,
schema: Blog.Schema
end
Absinthe is a Plug, and you pass it one Schema.
Main concepts
Schema
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 will account for { posts { ··· } }
. It returns a Type of :post
, and delegates to a Resolver.
Resolver
web/resolvers/post_resolver.ex
defmodule Blog.PostResolver do
def all(_args, _info) do
{:ok, Blog.Repo.all(Blog.Post)}
end
end
This is the function that the schema delegated the posts
query to.
Type
web/schema/types.ex
defmodule Blog.Schema.Types do
use Absinthe.Schema.Notation
@desc "A blog post"
object :post do
field :id, :id
field :title, :string
field :body, :string
end
end
This defines a type :post
, which is used by the resolver.
Schema
Query arguments
GraphQL query
{ user(id: "1") { ··· } }
web/schema.ex
query do
field :user, type: :user do
arg :id, non_null(:id)
resolve &Blog.UserResolver.find/2
end
end
{: data-line="3"}
Resolver
def find(%{id: id} = args, _info) do
···
end
Mutations
GraphQL query
{
mutation CreatePost {
post(title: "Hello") { id }
}
}
web/schema.ex
mutation do
@desc "Create a post"
field :post, type: :post do
arg :title, non_null(:string)
resolve &Blog.PostResolver.create/2
end
end