Thanks! We'll be in touch in the next 12 hours
Oops! Something went wrong while submitting the form.

Creating GraphQL APIs Using Elixir Phoenix and Absinthe

Pratik Narode

Full-stack Development

Introduction

GraphQL is a new hype in the Field of API technologies. We have been constructing and using REST API's for quite some time now and started hearing about GraphQL recently. GraphQL is usually described as a frontend-directed API technology as it allows front-end developers to request data in a more simpler way than ever before. The objective of this query language is to formulate client applications formed on an instinctive and adjustable format, for portraying their data prerequisites as well as interactions.

The Phoenix Framework is running on Elixir, which is built on top of Erlang. Elixir core strength is scaling and concurrency. Phoenix is a powerful and productive web framework that does not compromise speed and maintainability. Phoenix comes in with built-in support for web sockets, enabling you to build real-time apps.

Prerequisites:

  1. Elixir & Erlang: Phoenix is built on top of these
  2. Phoenix Web Framework: Used for writing the server application. (It's a well-unknown and lightweight framework in elixir) 
  3. Absinthe: GraphQL library written for Elixir used for writing queries and mutations.
  4. GraphiQL: Browser based GraphQL ide for testing your queries. Consider it similar to what Postman is used for testing REST APIs.

Overview:

The application we will be developing is a simple blog application written using Phoenix Framework with two schemas User and Post defined in Accounts and Blog resp. We will design the application to support API's related to blog creation and management. Assuming you have Erlang, Elixir and mix installed.

Where to Start:

At first, we have to create a Phoenix web application using the following command:

CODE: https://gist.github.com/velotiotech/89490334dd2cec11a98653b66d64dd72.js

--no-brunch - do not generate brunch files for static asset building. When choosing this option, you will need to manually handle JavaScript  dependencies if building HTML apps

• --no-html - do not generate HTML views.

Note: As we are going to mostly work with API, we don't need any web pages, HTML views and so the command args  and

Dependencies:

After we create the project, we need to add dependencies in mix.exs to make GraphQL available for the Phoenix application.

CODE: https://gist.github.com/velotiotech/f7eea6933f9fbb482ad07d4e80c16573.js

Structuring the Application:

We can used following components to design/structure our GraphQL application:

  1. GraphQL Schemas : This has to go inside lib/graphql_web/schema/schema.ex. The schema definitions your queries and mutations.
  2. Custom types: Your schema may include some custom properties which should be defined inside lib/graphql_web/schema/types.ex

Resolvers: We have to write respective Resolver Function’s that handles the business logic and has to be mapped with respective query or mutation. Resolvers should be defined in their own files. We defined it inside lib/graphql/accounts/user_resolver.ex and lib/graphql/blog/post_resolver.ex folder.

Also, we need to uppdate the router we have to be able to make queries using the GraphQL client in lib/graphql_web/router.ex and also have to create a GraphQL pipeline to route the API request which also goes inside lib/graphql_web/router.ex:

CODE: https://gist.github.com/velotiotech/333fc99bfc0525469ac028f2f1d08c4e.js

Writing GraphQL Queries:

Lets write some graphql queries which can be considered to be equivalent to GET requests in REST. But before getting into queries lets take a look at GraphQL schema we defined and its equivalent resolver mapping:

CODE: https://gist.github.com/velotiotech/dc1fed4d21e383e4a7203df36060e18f.js

You can see above we have defined four queries in the schema. Lets pick a query and see what goes into it :

CODE: https://gist.github.com/velotiotech/d9f1864f188ce314aa7b14bf148d428f.js

Above, we have retrieved a particular user using his email address through Graphql query.

  1. arg(:, ): defines an non-null incoming string argument i.e user email for us.
  2. Graphql.Accounts.UserResolver.find/2 : the resolver function that is mapped via schema, which contains the core business logic for retrieving an user.
  3. Accounts_user : the custome defined type which is defined inside lib/graphql_web/schema/types.ex as follows:

CODE: https://gist.github.com/velotiotech/200a6d81d4426fc02b3efe847081ad35.js

We need to write a separate resolver function for every query we define. Will go over the resolver function for accounts_user which is present in lib/graphql/accounts/user_resolver.ex file:

CODE: https://gist.github.com/velotiotech/66182707c22f13532d3290d3aaca15cb.js

This function is used to list all users or retrieve a particular user using an email address. Let’s run it now using GraphiQL browser. You need to have the server running on port 4000. To start the Phoenix server use:

CODE: https://gist.github.com/velotiotech/fc822fc705c6130635f76af503f5db3d.js

Let’s retrieve an user using his email address via query:

Writing GraphQL Queries

Above, we have retrieved the id, email and name fields by executing accountsUser query with an email address. GraphQL also allow us to define variables which we will show later when writing different mutations.

Let’s execute another query to list all blog posts that we have defined:

GraphQL Queries

 Writing GraphQL Mutations:

Let's write some GraphQl mutations. If you have understood the way graphql queries are written mutations are much simpler and similar to queries and easy to understand. It is defined in the same form as queries with a resolver function. Different mutations we are gonna write are as follow:

  1. create_post:- create a new blog post
  2. update_post :- update a existing blog post
  3. delete_post:- delete an existing blog post

The mutation looks as follows:

CODE: https://gist.github.com/velotiotech/c39344c524d9c6d2b71440eb983f42dd.js

Let's run some mutations to create a post in GraphQL:

Writing GraphQL Mutations

Notice the method is POST and not GET over here.

Let's dig into update mutation function :

CODE: https://gist.github.com/velotiotech/746af69881225144095e6aeff7617f19.js

Here, update post takes two arguments as input ,  non null id and a post parameter of type update_post_params that holds the input parameter values to update. The mutation is defined in lib/graphql_web/schema/schema.ex while the input parameter values are defined in lib/graphql_web/schema/types.ex —

CODE: https://gist.github.com/velotiotech/c0eca85ebbe846f13901efad22688b57.js

The difference with previous type definitions is that it’s defined as input_object instead of object.

The corresponding resolver function is defined as follows :

CODE: https://gist.github.com/velotiotech/e9efd0c7c2d71ce4e880887f2f4f2226.js

     

GraphQL Functions

Here we have defined a query parameter to specify the id of the blog post to be updated.

Conclusion

This is all you need, to write a basic GraphQL server for any Phoenix application using Absinthe.  

References:

  1. https://www.howtographql.com/graphql-elixir/0-introduction/
  2. https://pragprog.com/book/wwgraphql/craft-graphql-apis-in-elixir-with-absinthe
  3. https://itnext.io/graphql-with-elixir-phoenix-and-absinthe-6b0ffd260094
Get the latest engineering blogs delivered straight to your inbox.
No spam. Only expert insights.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings

Creating GraphQL APIs Using Elixir Phoenix and Absinthe

Introduction

GraphQL is a new hype in the Field of API technologies. We have been constructing and using REST API's for quite some time now and started hearing about GraphQL recently. GraphQL is usually described as a frontend-directed API technology as it allows front-end developers to request data in a more simpler way than ever before. The objective of this query language is to formulate client applications formed on an instinctive and adjustable format, for portraying their data prerequisites as well as interactions.

The Phoenix Framework is running on Elixir, which is built on top of Erlang. Elixir core strength is scaling and concurrency. Phoenix is a powerful and productive web framework that does not compromise speed and maintainability. Phoenix comes in with built-in support for web sockets, enabling you to build real-time apps.

Prerequisites:

  1. Elixir & Erlang: Phoenix is built on top of these
  2. Phoenix Web Framework: Used for writing the server application. (It's a well-unknown and lightweight framework in elixir) 
  3. Absinthe: GraphQL library written for Elixir used for writing queries and mutations.
  4. GraphiQL: Browser based GraphQL ide for testing your queries. Consider it similar to what Postman is used for testing REST APIs.

Overview:

The application we will be developing is a simple blog application written using Phoenix Framework with two schemas User and Post defined in Accounts and Blog resp. We will design the application to support API's related to blog creation and management. Assuming you have Erlang, Elixir and mix installed.

Where to Start:

At first, we have to create a Phoenix web application using the following command:

CODE: https://gist.github.com/velotiotech/89490334dd2cec11a98653b66d64dd72.js

--no-brunch - do not generate brunch files for static asset building. When choosing this option, you will need to manually handle JavaScript  dependencies if building HTML apps

• --no-html - do not generate HTML views.

Note: As we are going to mostly work with API, we don't need any web pages, HTML views and so the command args  and

Dependencies:

After we create the project, we need to add dependencies in mix.exs to make GraphQL available for the Phoenix application.

CODE: https://gist.github.com/velotiotech/f7eea6933f9fbb482ad07d4e80c16573.js

Structuring the Application:

We can used following components to design/structure our GraphQL application:

  1. GraphQL Schemas : This has to go inside lib/graphql_web/schema/schema.ex. The schema definitions your queries and mutations.
  2. Custom types: Your schema may include some custom properties which should be defined inside lib/graphql_web/schema/types.ex

Resolvers: We have to write respective Resolver Function’s that handles the business logic and has to be mapped with respective query or mutation. Resolvers should be defined in their own files. We defined it inside lib/graphql/accounts/user_resolver.ex and lib/graphql/blog/post_resolver.ex folder.

Also, we need to uppdate the router we have to be able to make queries using the GraphQL client in lib/graphql_web/router.ex and also have to create a GraphQL pipeline to route the API request which also goes inside lib/graphql_web/router.ex:

CODE: https://gist.github.com/velotiotech/333fc99bfc0525469ac028f2f1d08c4e.js

Writing GraphQL Queries:

Lets write some graphql queries which can be considered to be equivalent to GET requests in REST. But before getting into queries lets take a look at GraphQL schema we defined and its equivalent resolver mapping:

CODE: https://gist.github.com/velotiotech/dc1fed4d21e383e4a7203df36060e18f.js

You can see above we have defined four queries in the schema. Lets pick a query and see what goes into it :

CODE: https://gist.github.com/velotiotech/d9f1864f188ce314aa7b14bf148d428f.js

Above, we have retrieved a particular user using his email address through Graphql query.

  1. arg(:, ): defines an non-null incoming string argument i.e user email for us.
  2. Graphql.Accounts.UserResolver.find/2 : the resolver function that is mapped via schema, which contains the core business logic for retrieving an user.
  3. Accounts_user : the custome defined type which is defined inside lib/graphql_web/schema/types.ex as follows:

CODE: https://gist.github.com/velotiotech/200a6d81d4426fc02b3efe847081ad35.js

We need to write a separate resolver function for every query we define. Will go over the resolver function for accounts_user which is present in lib/graphql/accounts/user_resolver.ex file:

CODE: https://gist.github.com/velotiotech/66182707c22f13532d3290d3aaca15cb.js

This function is used to list all users or retrieve a particular user using an email address. Let’s run it now using GraphiQL browser. You need to have the server running on port 4000. To start the Phoenix server use:

CODE: https://gist.github.com/velotiotech/fc822fc705c6130635f76af503f5db3d.js

Let’s retrieve an user using his email address via query:

Writing GraphQL Queries

Above, we have retrieved the id, email and name fields by executing accountsUser query with an email address. GraphQL also allow us to define variables which we will show later when writing different mutations.

Let’s execute another query to list all blog posts that we have defined:

GraphQL Queries

 Writing GraphQL Mutations:

Let's write some GraphQl mutations. If you have understood the way graphql queries are written mutations are much simpler and similar to queries and easy to understand. It is defined in the same form as queries with a resolver function. Different mutations we are gonna write are as follow:

  1. create_post:- create a new blog post
  2. update_post :- update a existing blog post
  3. delete_post:- delete an existing blog post

The mutation looks as follows:

CODE: https://gist.github.com/velotiotech/c39344c524d9c6d2b71440eb983f42dd.js

Let's run some mutations to create a post in GraphQL:

Writing GraphQL Mutations

Notice the method is POST and not GET over here.

Let's dig into update mutation function :

CODE: https://gist.github.com/velotiotech/746af69881225144095e6aeff7617f19.js

Here, update post takes two arguments as input ,  non null id and a post parameter of type update_post_params that holds the input parameter values to update. The mutation is defined in lib/graphql_web/schema/schema.ex while the input parameter values are defined in lib/graphql_web/schema/types.ex —

CODE: https://gist.github.com/velotiotech/c0eca85ebbe846f13901efad22688b57.js

The difference with previous type definitions is that it’s defined as input_object instead of object.

The corresponding resolver function is defined as follows :

CODE: https://gist.github.com/velotiotech/e9efd0c7c2d71ce4e880887f2f4f2226.js

     

GraphQL Functions

Here we have defined a query parameter to specify the id of the blog post to be updated.

Conclusion

This is all you need, to write a basic GraphQL server for any Phoenix application using Absinthe.  

References:

  1. https://www.howtographql.com/graphql-elixir/0-introduction/
  2. https://pragprog.com/book/wwgraphql/craft-graphql-apis-in-elixir-with-absinthe
  3. https://itnext.io/graphql-with-elixir-phoenix-and-absinthe-6b0ffd260094

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings