How to expose graphql field with different name

Amit Kumar picture Amit Kumar · Dec 19, 2017 · Viewed 24.1k times · Source

I am exploring GraphQL and would like to know if there is any way of renaming the response field for example i have a POJO with these field

class POJO {
  Long id;
  String name;
}

GraphQL query:

type POJO {
  id: Long
  name: String
}

My response is something like this

{
  "POJO" {
    "id": 123,
    "name": "abc"
  }
}

Can i rename the name field to something like userName so that my response is below

{
  "POJO" {
    "id": 123,
    "userName": "abc"
  }
}

Answer

marktani picture marktani · Dec 19, 2017

You can use GraphQL Aliases to modify individual keys in the JSON response.

If this is your original query

query {
  POJO {
    id
    name
  }
}

you can introduce a GraphQL alias userName for the field name like so:

query {
  POJO {
    id
    userName: name
  }
}

You can also use GraphQL aliases to use the same query or mutation field multiple times in the same GraphQL operation. This get's especially interesting when using field parameters:

query {
  first: POJO(first: 1) {
    id
    name
  }

  second: POJO(first: 1, skip: 1) {
    id
    name
  }
}