本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

SpringBoot怎么使用GraphQL开发Web API

网络教程 app 1℃

SpringBoot怎么使用GraphQL开发Web API
前言

传统的restful api 存在诸多的问题,首先它无法控制返回的字段,前端也无法预判后端的返回结果,另外不同的返回结果对应不同的请求地址,这就导致了多次请求的问题。而graphql正是基于这样的背景而构建出来的api查询语言,相对于传统restful api 它具有以下几个优点:

灵活性:GraphQL 可以根据客户端的需求灵活地查询数据,而不是像 RESTful API 那样返回固定结构的数据。

减少网络请求:GraphQL 允许客户端在一次请求中获取多个资源,这有助于减少网络请求的数量和提高性能。

强类型:GraphQL 有一种强类型系统,客户端可以在编译时检测到查询中的错误,这有助于减少运行时错误。

可缓存:GraphQL 具有可缓存性,这意味着服务器可以缓存查询的结果,从而提高性能和可伸缩性。

文档化:GraphQL 具有自我文档化的能力,使得开发者可以快速了解 API 的结构和功能。

Spring Boot中GraphQL的实现方案

如果后端语言为Java,那么GraphQL Java则是实现GraphQL的基础库。另外Spring已经整合了GraphQL,如果项目中使用了Spring,那么更加推荐Spring GraphQL。

Spring GraphQL的开发总体分为如下几个步骤

添加 Spring GraphQL 依赖项

在您的项目中添加 Spring GraphQL 依赖项。您可以通过 Maven 或 Gradle 等构建工具来添加依赖项。例如,如果您使用 Maven,则可以添加以下依赖项

        <dependency>            <groupid>org.springframework.boot</groupid>            <artifactid>spring-boot-starter-graphql</artifactid>        </dependency>

定义 GraphQL Schema

在您的应用程序中定义 GraphQL Schema。Schema 定义了可查询的类型和字段。您可以使用 SDL(Schema Definition Language)或编程方式定义 Schema。

对于Spring Boot 工程来说schema文件放到resources/graphql/目录下,文件名后缀graphqls,下面是我定义一个的简单的schema.graphqls。

它指定了两个查询实现,author(id:Int)表示通过id查询Author,allAuthors则表示查询Author数组。

schema {    query: Query}type Query {    author(id:Int): Author    allAuthors: [Author]}type Author {    id:Int    firstName:String    lastName:String    email:String    birthdate:String}

实现RuntimeWiringConfigurer

RuntimeWiringConfigurer是实现GraphQL获取数据的核心,使用GraphQL并不能直接去掉Mybatis/Jpa这类持久层框架,从数据库获取数据仍然需要这类框架的支持。

而RuntimeWiringConfigurer则类似于Spring中的service层,它是实现基础数据的核心。

以下是一个简单示例:

@Componentpublic class AuthorWiring implements RuntimeWiringConfigurer {    private final AuthorRepository authorRepository;    public AuthorWiring(AuthorRepository authorRepository) {        this.authorRepository = authorRepository;    }    @Override    public void configure(RuntimeWiring.Builder builder) {        builder.type("Query", typeWiring -&gt; typeWiring                        .dataFetcher("allAuthors", environment -&gt; authorRepository.findAll())                        .dataFetcher("author", environment -&gt; authorRepository.getReferenceById(environment.getArgument("id")))    }}

这里configure方法内部分别定义了两个DataFetcher对象,用来指定author和allAuthors查询数据的方式,可以看出依然是通过JPA去查询数据。

定义GraphQL Controller

我么定义GraphQLController用来接收web请求的入参,示例如下:

@RestController@RequestMapping("graphql")public class GraphQLController {    private final GraphQL graphQL;    @Autowired    public GraphQLController(GraphQlSource graphQlSource) {        graphQL = graphQlSource.graphQl();    }    @PostMapping("query")    public ResponseEntity<object> query(@RequestBody String query) {        ExecutionResult result = graphQL.execute(query);        return ResponseEntity.ok(result.getData());    }}</object>

代码中GraphQL对象是执行查询的入口,但GraphQL只有一个私有的构造方法,所以不能直接注入,必须通过注入GraphQlSource的方式来获取GraphQL对象。

注意在GraphQL中我们只能使用String来接收参数,无法使用model对象,这是因为Graph请求参数并不是json结构。

测试Graph请求

我们创建一个graphql.http的文件,用于在idea中执行http请求

### Send POST request with json body
POST localhost:8080/graphql/query
Content-Type: application/json

{
  author(id: 1) {
    id
    firstName
    lastName
    birthdate
  }
}

### Send POST request with json body
POST localhost:8080/graphql/query
Content-Type: application/json

{
  allAuthors {
    id
    firstName
    lastName
    birthdate
  }
}

运行author(id: 1) 的查询,可以看到正常返回结果了。如果我们只需要 firstName和lastName两个字段,那么在请求入参中直接去掉id和birthdate就好了,而不用改动任何后端代码。

以上就是SpringBoot怎么使用GraphQL开发Web API的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » SpringBoot怎么使用GraphQL开发Web API

喜欢 (0)