Hello, everyone, I am Xiao Hei, meet you again ~

A new topic is about GraphQL. It is mainly about developing GraphQL applications quickly through Spring Boot. I hope it will be helpful to students who are new to GraphQL.

Github address: github.com/shenjianeng…

What is a GraphQL

Take a look at the explanation on the official website:

graphql.org/

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.cn/

GraphQL is both a query language for the API and a runtime for your data queries. GraphQL provides an easy-to-understand set of complete descriptions of the data in your API, enabling a client to get exactly what it needs without any redundancy, making it easier for the API to evolve over time, and for building powerful developer tools.

Take another look at wikipedia’s explanation:

En.wikipedia.org/wiki/GraphQ…

GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data.GraphQL was developed internally by Facebook in 2012 before being publicly released in 2015.

It allows clients to define the structure of the data required, and the same structure of the data is returned from the server.

GraphQL is an open source data query and manipulation language for apis and a runtime for implementing existing data queries. GraphQL was developed internally by Facebook in 2012 and publicly released in 2015.

It allows the client to define the structure of the required data and return the same data structure from the server.

GraphQL = Graph + QL = graphical, visual query language. It allows the client to define the structure of the required data and return the same data structure from the server.

Hello world

GraphQL is a specification that is supported by multiple programming languages.

In this series of articles, we use graphQL-spring-boot-starter to complete the graphQL-related development tutorial.

Github address: github.com/graphql-jav…

Introducing dependent dependencies

Build a basic Spring Boot Web project project, introduce the latest graphQL-spring-boot-starter:

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>

  <dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-spring-boot-starter</artifactId>
    <version>8.0.0</version>
  </dependency>
Copy the code

Maven can be used to see what dependencies graphQL-spring-boot-starter has introduced:

Graphql-spring-boot-starter scans all graphQLS suffix files in the classpath by default.

Of course, we can also configure and modify the related properties through application.properties. In this case, we will use the default Settings.

Write your first graphqls file

Create a new schema.graphqls file in the Resources folder.

If you’re using the idea, you can install plugins.jetbrains.com/plugin/8097… Plugins to help you write graphqls files.

Type user {# id, the type is id,! Id :ID! Username :String! nickname:String! City: city} # city enumeration value enum city {hangzhou Shanghai} Return user array userList:[user!] }Copy the code

The User and City data types are defined in the schema.graphqls file above. At the same time, we generate two Java beans to correspond to it.

public enum City {
    hangzhou,
    shanghai,
}

@Data
public class User {
    private UUID id;
    private String username;
    private String nickname;
    private City city;
}
Copy the code

Define GraphQLQueryResolver

@Component
public class UserGraphQLQueryResolver implements GraphQLQueryResolver {

    public Collection<User> userList(a) {
        User user1 = new User();
        user1.setId(UUID.randomUUID());
        user1.setUsername("Coder black");
        user1.setNickname(Coder Black has no nickname);
        user1.setCity(City.hangzhou);

        User user2 = new User();
        user2.setId(UUID.randomUUID());
        user2.setUsername("Fight tiger tonight.");
        user2.setNickname("Love tiger oil");
        user2.setCity(City.shanghai);
        returnArrays.asList(user1, user2); }}Copy the code
  • A Spring Beran is definedUserGraphQLQueryResolverTo achieve thegraphql.kickstart.tools.GraphQLQueryResolverinterface
  • There’s a group calleduserListMethod, which does not need an input parameter, returnsCollection<User>

That’s right, smart readers have already figured out:

UserGraphQLQueryResolver#userList is used to match the query to get a list of users defined in schema.graphqls.

Use GRAPhiQL to request the server

Graphiql makes it easy to make requests to the GraphQL server. It is also easy to use.

  <dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphiql-spring-boot-starter</artifactId>
    <version>8.0.0</version>
    <scope>runtime</scope>
  </dependency>
Copy the code

Well, let’s start the Spring Boot application, visit http://localhost:8080/graphiql

In github.com/graphql-jav… Implementing a GraphQL service is as simple as that.

Customize the Servlet Mapping address

Let’s take a look at what the client request looks like:

In the meantime, we can change the server’s request receiving path via the application.properties file:

graphql.servlet.mapping=/coder-xiao-hei
Copy the code

Implemented using native GraphQL

Let’s use GraphQL’s native API to implement the above example.

public class HelloWorld {

    static Collection<User> userList(a) {
        User user1 = new User();
        user1.setId(UUID.randomUUID());
        user1.setUsername("Coder black");
        user1.setNickname(Coder Black has no nickname);
        user1.setCity(City.hangzhou);
        return Collections.singletonList(user1);
    }

    public static void main(String[] args) throws IOException {
        Resource resource = new DefaultResourceLoader().getResource("classpath:schema.graphqls");
        String schema = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);

        SchemaParser schemaParser = new SchemaParser();
        TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

        RuntimeWiring runtimeWiring =
                RuntimeWiring.newRuntimeWiring()
                        .type(TypeRuntimeWiring
                                .newTypeWiring("Query")
                                .dataFetcher("userList",
                                        (DataFetcher<Collection<User>>) environment -> userList()))
                        .build();

        SchemaGenerator schemaGenerator = new SchemaGenerator();
        GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

        GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
        ExecutionResult executionResult = build.execute("query{\n" +
                " userList{\n" +
                " id\n" +
                " username\n" +
                " }\n" +
                "}");

        // {userList=[{id=486a181e-eec7-4001-a9d9-65e94a004f8c, username=coder}]}System.out.println(executionResult.getData().toString()); }}Copy the code

The following diagram clearly describes the relationship between the related components in the above application:

Next up

In the next installment, we’ll use graphQL to implement simple add, delete, alter, and custom scalar types. Thanks for your attention and reading ~~

References:

Github.com/graphql-jav…

graphql.org

www.graphql-java.com/tutorials/g…

Graphql.org/code/#java-…