GraphQL是Rest API的查询语言,它使客户端可以选择所需的确切功能。 它还提供了服务器端运行时来执行查询。
GraphQL包含3个主要部分
- 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应用程序中集成GraphQL。 因此,让我们从GraphQL模式文件开始。
代码结构如下所示
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控制器的端点并开始执行查询
我们可以要求响应字段,graphql将仅服务于选定的字段。
- 查询用户仅名称
- 查询用户的所有字段
我们可以在单个请求中请求多个查询
甚至多次使用别名查询
You can find complete code here
快乐编码😀😀😀!