Working with GraphQL aliases

Rachita Bansal
2 min readJun 12, 2018

This article will go through a use-case where having aliases can be very useful in the GraphQL query. I have been working on a graphQL project for over a month now and recently came across the need of using aliases and thought of sharing it.

A query in GraphQL has different components such as arguments, directives, fields and fragments. Let’s say we have a scenario where we want to get the data on an object type but with different arguments in the same query. For example, we have a schema in which an Employee can be a Manager or Engineer. The below query would run perfectly fine for the above use-case.

GraphQL Schema for Employees object

Let say we have to get all the employees based on their positions. In this case we could query the server passing the position as an argument to the query. This filters data on position of the employee and gets you the results based on the filters within a single query. Let’s look at the query below.

Query based on different arguments without use of aliases return an error

The above would return an error because GraphQL expects different field name. Due to the conflicting behavior of the field names cannot differentiate between objects as two separate fields. We can resolve this by using aliases and still get the results in a single query. The query below shows how to define aliases in a query.

Query using aliases

The above query would resolve the conflict as now the field names are different and returns an array which looks something like below.

Query results with aliases

--

--

Rachita Bansal

Software Engineer @ Microsoft | Full-Stack | Data viz| Node.js | React | GraphQL | UI/UX