Quarkus - GraphQL

This guide demonstrates how your Quarkus application can utilize the Eclipse MicroProfile GraphQL specification through the SmallRye GraphQL extension.

As the GraphQL specification website states:

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

GraphQL was originally developed by Facebook in 2012 and has been an open standard since 2015.

GraphQL is not a replacement for REST API specification but merely an alternative. Unlike REST, GraphQL API’s have the ability to benefit the client by:

Preventing Over-fetching and Under-fetching

REST API’s are server-driven fixed data responses that cannot be determined by the client. Although the client does not require all the fields the client must retrieve all the data hence Over-fetching. A client may also require multiple REST API calls according to the first call (HATEOAS) to retrieve all the data that is required thereby Under-fetching.

API Evolution

Since GraphQL API’s returns data that are requested by the client adding additional fields and capabilities to existing API will not create breaking changes to existing clients.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

Architecture

In this guide, we build a simple GraphQL application that exposes a GraphQL API at /graphql.

This example was inspired by a popular GraphQL API.

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the microprofile-graphql-quickstart directory.

Creating the Maven Project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=microprofile-graphql-quickstart \
  4. -DclassName="org.acme.microprofile.graphql.FilmResource" \
  5. -Dextensions="graphql"
  6. cd microprofile-graphql-quickstart

This command generates a Maven project, importing the smallrye-graphql extension which is an implementation of the MicroProfile GraphQL specification used in Quarkus.

If you already have your Quarkus project configured, you can add the smallrye-graphql extension to your project by running the following command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="graphql"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-smallrye-graphql</artifactId>
  4. </dependency>

Preparing an Application: GraphQL API

In this section we will start creating the GraphQL API.

First, create the following entities representing a film from a galaxy far far away:

  1. package org.acme.microprofile.graphql;
  2. public class Film {
  3. private String title;
  4. private Integer episodeID;
  5. private String director;
  6. private LocalDate releaseDate;
  7. public String getTitle() {
  8. return title;
  9. }
  10. public void setTitle(String title) {
  11. this.title = title;
  12. }
  13. public Integer getEpisodeID() {
  14. return episodeID;
  15. }
  16. public void setEpisodeID(Integer episodeID) {
  17. this.episodeID = episodeID;
  18. }
  19. public String getDirector() {
  20. return director;
  21. }
  22. public void setDirector(String director) {
  23. this.director = director;
  24. }
  25. public LocalDate getReleaseDate() {
  26. return releaseDate;
  27. }
  28. public void setReleaseDate(LocalDate releaseDate) {
  29. this.releaseDate = releaseDate;
  30. }
  31. }
  32. public class Hero {
  33. private String name;
  34. private String surname;
  35. private Double height;
  36. private Integer mass;
  37. private Boolean darkSide;
  38. private LightSaber lightSaber;
  39. private List<Integer> episodeIds = new ArrayList<>();
  40. public String getName() {
  41. return name;
  42. }
  43. public void setName(String name) {
  44. this.name = name;
  45. }
  46. public String getSurname() {
  47. return surname;
  48. }
  49. public void setSurname(String surname) {
  50. this.surname = surname;
  51. }
  52. public Double getHeight() {
  53. return height;
  54. }
  55. public void setHeight(Double height) {
  56. this.height = height;
  57. }
  58. public Integer getMass() {
  59. return mass;
  60. }
  61. public void setMass(Integer mass) {
  62. this.mass = mass;
  63. }
  64. public Boolean getDarkSide() {
  65. return darkSide;
  66. }
  67. public void setDarkSide(Boolean darkSide) {
  68. this.darkSide = darkSide;
  69. }
  70. public LightSaber getLightSaber() {
  71. return lightSaber;
  72. }
  73. public void setLightSaber(LightSaber lightSaber) {
  74. this.lightSaber = lightSaber;
  75. }
  76. public List<Integer> getEpisodeIds() {
  77. return episodeIds;
  78. }
  79. public void setEpisodeIds(List<Integer> episodeIds) {
  80. this.episodeIds = episodeIds;
  81. }
  82. }
  83. enum LightSaber {
  84. RED, BLUE, GREEN
  85. }

The classes we have just created describe the GraphQL schema which is a set of possible data (objects, fields, relationships) that a client can access.

Let’s continue with an example CDI bean, that would work as a repository:

  1. @ApplicationScoped
  2. public class GalaxyService {
  3. private List<Hero> heroes = new ArrayList<>();
  4. private List<Film> films = new ArrayList<>();
  5. public GalaxyService() {
  6. Film aNewHope = new Film();
  7. aNewHope.setTitle("A New Hope");
  8. aNewHope.setReleaseDate(LocalDate.of(1977, Month.MAY, 25));
  9. aNewHope.setEpisodeID(4);
  10. aNewHope.setDirector("George Lucas");
  11. Film theEmpireStrikesBack = new Film();
  12. theEmpireStrikesBack.setTitle("The Empire Strikes Back");
  13. theEmpireStrikesBack.setReleaseDate(LocalDate.of(1980, Month.MAY, 21));
  14. theEmpireStrikesBack.setEpisodeID(5);
  15. theEmpireStrikesBack.setDirector("George Lucas");
  16. Film returnOfTheJedi = new Film();
  17. returnOfTheJedi.setTitle("Return Of The Jedi");
  18. returnOfTheJedi.setReleaseDate(LocalDate.of(1983, Month.MAY, 25));
  19. returnOfTheJedi.setEpisodeID(6);
  20. returnOfTheJedi.setDirector("George Lucas");
  21. films.add(aNewHope);
  22. films.add(theEmpireStrikesBack);
  23. films.add(returnOfTheJedi);
  24. Hero luke = new Hero();
  25. luke.setName("Luke");
  26. luke.setSurname("Skywalker");
  27. luke.setHeight(1.7);
  28. luke.setMass(73);
  29. luke.setLightSaber(LightSaber.GREEN);
  30. luke.setDarkSide(false);
  31. luke.getEpisodeIds().addAll(Arrays.asList(4, 5, 6));
  32. Hero leia = new Hero();
  33. leia.setName("Leia");
  34. leia.setSurname("Organa");
  35. leia.setHeight(1.5);
  36. leia.setMass(51);
  37. leia.setDarkSide(false);
  38. leia.getEpisodeIds().addAll(Arrays.asList(4, 5, 6));
  39. Hero vader = new Hero();
  40. vader.setName("Darth");
  41. vader.setSurname("Vader");
  42. vader.setHeight(1.9);
  43. vader.setMass(89);
  44. vader.setDarkSide(true);
  45. vader.setLightSaber(LightSaber.RED);
  46. vader.getEpisodeIds().addAll(Arrays.asList(4, 5, 6));
  47. heroes.add(luke);
  48. heroes.add(leia);
  49. heroes.add(vader);
  50. }
  51. public List<Film> getAllFilms() {
  52. return films;
  53. }
  54. public Film getFilm(int id) {
  55. return films.get(id);
  56. }
  57. public List<Hero> getHeroesByFilm(Film film) {
  58. return heroes.stream()
  59. .filter(hero -> hero.getEpisodeIds().contains(film.getEpisodeID()))
  60. .collect(Collectors.toList());
  61. }
  62. public void addHero(Hero hero) {
  63. heroes.add(hero);
  64. }
  65. public Hero deleteHero(int id) {
  66. return heroes.remove(id);
  67. }
  68. public List<Hero> getHeroesBySurname(String surname) {
  69. return heroes.stream()
  70. .filter(hero -> hero.getSurname().equals(surname))
  71. .collect(Collectors.toList());
  72. }
  73. }

Now, let’s create our first GraphQL API.

Edit the org.acme.microprofile.graphql.FilmResource class as following:

  1. @GraphQLApi (1)
  2. public class FilmResource {
  3. @Inject
  4. GalaxyService service;
  5. @Query("allFilms") (2)
  6. @Description("Get all Films from a galaxy far far away") (3)
  7. public List<Film> getAllFilms() {
  8. return service.getAllFilms();
  9. }
  10. }
1@GraphQLApi annotation indicates that the CDI bean will be a GraphQL endpoint
2@Query annotation defines that this method will be queryable with the name allFilms
3Documentation of the queryable method
The value of the @Query annotation is optional and would implicitly be defaulted to the method name if absent.

This way we have created our first queryable API which we will later expand.

Launch

Launch the quarkus app:

  1. ./mvnw compile quarkus:dev

Introspect

The full schema of the GraphQL API can be retrieved by calling the following:

  1. curl http://localhost:8080/graphql/schema.graphql

The server will return the complete schema of the GraphQL API.

GraphiQL UI

Experimental - not included in the MicroProfile specification

GraphiQL UI is a great tool permitting easy interaction with your GraphQL APIs.

The Quarkus smallrye-graphql extension ships with GraphiQL and enables it by default in dev and test modes, but it can also be explicitly configured for production mode as well.

GraphiQL can be accessed from http://localhost:8080/graphql-ui/ .

GraphQL UI

Query the GraphQL API

Now visit the GraphiQL page that has been deployed in dev mode.

Enter the following query to GraphiQL and press the play button:

  1. query allFilms {
  2. allFilms {
  3. title
  4. director
  5. releaseDate
  6. episodeID
  7. }
  8. }

Since our query contains all the fields in the Film class we will retrieve all the fields in our response. Since GraphQL API responses are client determined, the client can choose which fields it will require.

Let’s assume that our client only requires title and releaseDate making the previous call to the API Over-fetching of unnecessary data.

Enter the following query into GraphiQL and hit the play button:

  1. query allFilms {
  2. allFilms {
  3. title
  4. releaseDate
  5. }
  6. }

Notice in the response we have only retrieved the required fields. Therefore, we have prevented Over-fetching.

Let’s continue to expand our GraphQL API by adding the following to the FilmResource class.

  1. @Query
  2. @Description("Get a Films from a galaxy far far away")
  3. public Film getFilm(@Name("filmId") int id) {
  4. return service.getFilm(id);
  5. }
Notice how we have excluded the value in the @Query annotation. Therefore, the name of the query is implicitly set as the method name excluding the get.

This query will allow the client to retrieve the film by id.

Enter the following into GraphiQL and make a request.

  1. query getFilm {
  2. film(filmId: 1) {
  3. title
  4. director
  5. releaseDate
  6. episodeID
  7. }
  8. }

The film query method requested fields can be determined as such in our previous example. This way we can retrieve individual film information.

However, say our client requires both films with filmId 0 and 1. In a REST API the client would have to make two calls to the API. Therefore, the client would be Under-fetching.

In GraphQL it is possible to make multiple queries at once.

Enter the following into GraphiQL to retrieve two films:

  1. query getFilms {
  2. film0: film(filmId: 0) {
  3. title
  4. director
  5. releaseDate
  6. episodeID
  7. }
  8. film1: film(filmId: 1) {
  9. title
  10. director
  11. releaseDate
  12. episodeID
  13. }
  14. }

This enabled the client to fetch the required data in a single request.

Expanding the API

Until now, we have created a GraphQL API to retrieve film data. We now want to enable the clients to retrieve the Hero data of the Film.

Add the following to our FilmResource class:

  1. public List<Hero> heroes(@Source Film film) { (1)
  2. return service.getHeroesByFilm(film);
  3. }
1Enable List<Hero> data to be added to queries that respond with Film

By adding this method we have effectively changed the schema of the GraphQL API. Although the schema has changed the previous queries will still work. Since we only expanded the API to be able to retrieve the Hero data of the Film.

Enter the following into GraphiQL to retrieve the film and hero data.

  1. query getFilmHeroes {
  2. film(filmId: 1) {
  3. title
  4. director
  5. releaseDate
  6. episodeID
  7. heroes {
  8. name
  9. height
  10. mass
  11. darkSide
  12. lightSaber
  13. }
  14. }
  15. }

The response now includes the heroes of the film.

Mutations

Mutations are used when data is created, updated or deleted.

Let’s now add the ability to add and delete heroes to our GraphQL API.

Add the following to our FilmResource class:

  1. @Mutation
  2. public Hero createHero(Hero hero) {
  3. service.addHero(hero);
  4. return hero;
  5. }
  6. @Mutation
  7. public Hero deleteHero(int id) {
  8. return service.deleteHero(id);
  9. }

Enter the following into GraphiQL to insert a Hero:

  1. mutation addHero {
  2. createHero(hero: {
  3. name: "Han",
  4. surname: "Solo"
  5. height: 1.85
  6. mass: 80
  7. darkSide: false
  8. episodeIds: [4, 5, 6]
  9. }
  10. )
  11. {
  12. name
  13. surname
  14. }
  15. }

By using this mutation we have created a Hero entity in our service.

Notice how in the response we have retrieved the name and surname of the created Hero. This is because we selected to retrieve these fields in the response within the { } in the mutation query. This can easily be a server side generated field that the client may require.

Let’s now try deleting an entry:

  1. mutation DeleteHero {
  2. deleteHero(id :3){
  3. name
  4. surname
  5. }
  6. }

Similar to the createHero mutation method we also retrieve the name and surname of the hero we have deleted which is defined in { }.

Creating Queries by fields

Queries can also be done on individual fields. For example, let’s create a method to query heroes by their last name.

Add the following to our FilmResource class:

  1. @Query
  2. public List<Hero> getHeroesWithSurname(@DefaultValue("Skywalker") String surname) {
  3. return service.getHeroesBySurname(surname);
  4. }

By using the @DefaultValue annotation we have determined that the surname value will be Skywalker when the parameter is not provided.

Test the following queries with GraphiQL:

  1. query heroWithDefaultSurname {
  2. heroesWithSurname{
  3. name
  4. surname
  5. lightSaber
  6. }
  7. }
  8. query heroWithSurnames {
  9. heroesWithSurname(surname: "Vader") {
  10. name
  11. surname
  12. lightSaber
  13. }
  14. }

Context

You can get information about the GraphQL request anywhere in your code, using this experimental, SmallRye specific feature:

  1. @Inject
  2. Context context;

The context object allows you to get:

  • the original request (Query/Mutation)

  • the arguments

  • the path

  • the selected fields

  • any variables

This allows you to optimize the downstream queries to the datastore.

See the JavaDoc for more details.

GraphQL-Java

This context object also allows you to fall down to the underlying graphql-java features by using the leaky abstraction:

  1. DataFetchingEnvironment dfe = context.unwrap(DataFetchingEnvironment.class);

You can also get access to the underlying graphql-java during schema generation, to add your own features directly:

  1. public GraphQLSchema.Builder addMyOwnEnum(@Observes GraphQLSchema.Builder builder) {
  2. // Here add your own features directly, example adding an Enum
  3. GraphQLEnumType myOwnEnum = GraphQLEnumType.newEnum()
  4. .name("SomeEnum")
  5. .description("Adding some enum type")
  6. .value("value1")
  7. .value("value2").build();
  8. return builder.additionalType(myOwnEnum);
  9. }

By using the @Observer you can add anything to the Schema builder.

Map to Scalar

Another SmallRye specific experimental feature, allows you to map an existing scalar (that is mapped by the implementation to a certain Java type) to another type, or to map complex object, that would typically create a Type or Input in GraphQL, to an existing scalar.

Mapping an existing Scalar to another type:

  1. public class Movie {
  2. @ToScalar(Scalar.Int.class)
  3. Long idLongThatShouldChangeToInt;
  4. // ....
  5. }

Above will map the Long java type to an Int Scalar type, rather than the default BigInteger.

Mapping a complex object to a Scalar type:

  1. public class Person {
  2. @ToScalar(Scalar.String.class)
  3. Phone phone;
  4. // ....
  5. }

This will, rather than creating a Type or Input in GraphQL, map to a String scalar.

To be able to do the above, the Phone object needs to have a constructor that takes a String (or Int / Date / etc.), or have a setter method for the String (or Int / Date / etc.), or have a fromString (or fromInt / fromDate - depending on the Scalar type) static method.

For example:

  1. public class Phone {
  2. private String number;
  3. // Getters and setters....
  4. public static Phone fromString(String number) {
  5. Phone phone = new Phone();
  6. phone.setNumber(number);
  7. return phone;
  8. }
  9. }

See more about the @ToScalar feature in the JavaDoc.

Error code

You can add an error code on the error output in the GraphQL response by using the (SmallRye specific) @ErrorCode:

  1. @ErrorCode("some-business-error-code")
  2. public class SomeBusinessException extends RuntimeException {
  3. // ...
  4. }

When SomeBusinessException occurs, the error output will contain the Error code:

  1. {
  2. "errors": [
  3. {
  4. "message": "Unexpected failure in the system. Jarvis is working to fix it.",
  5. "locations": [
  6. {
  7. "line": 2,
  8. "column": 3
  9. }
  10. ],
  11. "path": [
  12. "annotatedCustomBusinessException"
  13. ],
  14. "extensions": {
  15. "exception": "io.smallrye.graphql.test.apps.error.api.ErrorApi$AnnotatedCustomBusinessException",
  16. "classification": "DataFetchingException",
  17. "code": "some-business-error-code" (1)
  18. }
  19. }
  20. ],
  21. "data": {
  22. ...
  23. }
  24. }
1The error code

Conclusion

MicroProfile GraphQL enables clients to retrieve the exact data that is required preventing Over-fetching and Under-fetching.

The GraphQL API can be expanded without breaking previous queries enabling easy API evolution.

Configuration Reference