GraphQL(Java)入门

本文介绍GraphQL作为REST API的替代方案,重点讲解其核心组成部分,包括服务器、模式和客户端。通过一个Spring应用集成示例,展示了如何定义模式、配置解析器及执行查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GraphQL是Rest API的查询语言,它使客户端可以选择所需的确切功能。 它还提供了服务器端运行时来执行查询。

GraphQL包含3个主要部分

  1. GraphQL服务器GraphQL模式客户

GraphQL Server

GraphQL服务器负责验证和执行查询,并根据客户需要返回响应。 客户端可以根据需要选择字段,服务器将仅返回那些选择的字段。

GraphQL Schema

GraphQL有一种特定的语言,称为GraphQL模式语言 to define schema. GraphQL schema consist of the queries and types. As a API owner we can decide what queries & types will be available to the consumer. The schema has default root object type called 询问包含所有查询。 一个示例架构是

#The root object
type Query {
    hello: String
    greet(name: String): String
}
 #Defined Type
type User{
    name: String
    age: Int
}

在上面的架构中,根对象是Query,它具有一个称为你好和方法迎接并且都返回String类型。 的迎接有一个输入参数名称这是一种字符串类型。 这意味着客户端可以在查询时传递任何字符串类型的参数迎接。

The User type is defined type which has 2 fields name and age. GraphQL supports several built-in types like String, Int, Float, Boolean, etc. Click here to read more about graphql schema and types.

对于查询类型中的每个字段或查询,将有相应的解析器,该解析器将在GraphQL Server上运行。

Client

客户是消费者。 由于GraphQL在Rest之上工作,因此任何rest客户端都可以查询graphql。 很少有工具可以很好地进行测试。 这些工具提供了自动补全功能,我们可以查看所有可能的查询和类型。 一些工具是图形语言,失眠。

GraphQL-Java in Action

下面的代码将向您展示如何在Spring应用程序中集成G​​raphQL。 因此,让我们从GraphQL模式文件开始。

代码结构如下所示

GraphQL code structure

Define schema file users.graphql
type Query {
    hello: String
    users(name: String): User
}

type User {
    name: String
    age: Int
    address: String
}

现在,开始配置GraphQL Java对象以及用于查询(您好和用户)的解析器。

Step 1: Read & parse schema file

文件名:GraphQLSchema.java

private TypeDefinitionRegistry readAndParseSchemaFile() throws Exception {
        String schemaString = ResourceUtils.readClasspathResourceContent("users.graphql");

        SchemaParser schemaParser = new SchemaParser();

        // parsing schema file and creating typeDefRegistery
        return schemaParser.parse(schemaString);
    }
Step 2: Configure Resolvers
private RuntimeWiring buildRuntimeWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type("Query", builder -> builder.dataFetchers(buildDataFetchers()))
                .build();
    }

    private Map<String, DataFetcher> buildDataFetchers() {
        Map<String, DataFetcher> dataFetchers = new HashMap<>();
        dataFetchers.put("hello", new StaticDataFetcher("Welcome to GraphQL world."));
        dataFetchers.put("users", env -> User.of("John", 28, "India"));
        return dataFetchers;
    }
Step 3: Prepare GraphQL object and execute query
private void setup() throws Exception {
        // We need to create GraphQLSchema Object but before that we need to configure resolvers 
        GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(readAndParseSchemaFile(), buildRuntimeWiring());
        graphQL = GraphQL.newGraphQL(graphQLSchema).build();
    }

    public ExecutionResult executeQuery(String graphQLQuery) {
        return graphQL.execute(graphQLQuery);
    }
Step 4: Serve user queries on the endpoint (/graphql)
@RestController
    public class GraphQLController {

        private final GraphQLService graphQLService;

        @Autowired
        public GraphQLController(GraphQLService graphQLService) {
            this.graphQLService = graphQLService;
        }

        @PostMapping("/graphql")
        public Map<String, Object> executeQuery(@RequestBody GraphQLRequest request) {
            return graphQLService.executeQuery(request.getQuery()).toSpecification();
        }
    }
Step 5: User GraphiQL or Rest to execute graphql query

GraphiQL资源链接

在GraphiQL中添加/ graphql控制器的端点并开始执行查询

Query hello

我们可以要求响应字段,graphql将仅服务于选定的字段。

  1. 查询用户仅名称

Name only

  1. 查询用户的所有字段

All fields

我们可以在单个请求中请求多个查询

Multiple queries

甚至多次使用别名查询

Duplicate queries

You can find complete code here

快乐编码😀😀😀!

from: https://dev.to//jeetmp3/getting-started-with-graphql-java-53j1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值