Examples

Elixir GraphQL API

Building a GraphQL API

Elixir GraphQL API with Absinthe supports typed queries.

Introduction to Absinthe and GraphQL

Absinthe is a powerful library for building GraphQL APIs in Elixir. It allows you to define schemas, types, and resolvers, enabling efficient data fetching through typed queries. In this tutorial, we will explore how to set up a GraphQL API in Elixir using Absinthe.

Setting Up Your Elixir Project

First, create a new Elixir project using Mix, Elixir's build tool, and include the necessary dependencies for Absinthe and Phoenix:

After setting up your project, add Absinthe and Absinthe Phoenix dependencies to your mix.exs file:

Run mix deps.get to install the dependencies.

Defining Your GraphQL Schema

In GraphQL, the schema is the core of your API. It defines what queries are available and what data can be fetched. Create a new file lib/my_graphql_app_web/schema.ex to define your schema:

This simple schema defines a single query hello that returns a string "world".

Creating a GraphQL Endpoint

To expose your GraphQL API, set up a route and endpoint. Modify your router file lib/my_graphql_app_web/router.ex to include a GraphQL endpoint:

This configuration forwards requests to /api/graphql to Absinthe.Plug, which will handle GraphQL queries.

Testing Your GraphQL API

With the endpoint set up, you can test your GraphQL API. Start your Phoenix server with mix phx.server and navigate to http://localhost:4000/api/graphql. You can use tools like GraphiQL or Postman to interact with your API.

This query should return a response with { "data": { "hello": "world" } }, indicating your GraphQL API is working correctly.

Previous
REST API