Spring Boot - Rest VS GraphQL

Insert image description here


Overview

REST (Representational State Transfer) and GraphQL are both API designs and interaction methods for building web services. They have different characteristics, advantages and disadvantages.

REST(Representational State Transfer)

  1. Architectural style : REST is an architectural style that emphasizes the separation of resource status and identification. It usually communicates based on the HTTP protocol.

  2. Resource-oriented : REST API models the application's data as a set of resources, each resource has a unique URL identifier, such as /users/1information representing user 1. Resource operations are usually performed using HTTP verbs, such as GET (get resources), POST (create resources), PUT (update resources) and DELETE (delete resources), etc.

  3. State-agnostic : REST is stateless, each request contains enough information to handle the request, and the server does not need to store the client's state.

  4. Data transfer : The client usually cannot choose the data to get, but the server decides which data to return to the client. This can result in excessive or insufficient data transfer.

  5. Versioning : API versioning often needs to be considered to ensure backward compatibility.

GraphQL

  1. Query language : GraphQL is a query language that allows the client to accurately specify the data it needs to obtain and does not obtain redundant data. The client can create a custom query to get the required data, which reduces the problem of over-transmitting data.

  2. Single entry point : GraphQL typically has only one entry point (usually /graphql), and clients can fetch data from multiple resources in a single request.

  3. Strong typing : GraphQL has a strong type system that defines available data types and query structures, which helps detect errors in advance.

  4. Real-time data : GraphQL supports real-time data query, allowing clients to subscribe to data changes.

  5. Self-describing : GraphQL APIs often provide self-describing capabilities, allowing clients to query the API's schema and documentation to better understand how to construct queries.

  6. Versioning : Since the client can choose which fields to fetch, the need for versioning is reduced to some extent as queries from existing clients will not be broken.

Choosing REST or GraphQL depends on your project needs and preferences. REST is generally simpler and suitable for simple APIs, while GraphQL offers greater flexibility and efficiency and is particularly suitable for complex data queries and real-time applications. Depending on the specifics of your project, you can choose one of these or use a combination of them.

Illustration

Insert image description here


Code

Spring Boot + Rest

To integrate REST in Spring Boot, you can use the Spring Web module, which provides support for building RESTful web services. Here is a simple example project:

  1. Create a Spring Boot project, either using Spring Initializer or manually.

  2. Add dependencies, making sure to pom.xmlinclude the following dependencies in the file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. Create a REST controller, for example:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyController {
    
    

    @GetMapping("/hello")
    public String sayHello() {
    
    
        return "Hello, REST!";
    }
}
  1. Start the application and access http://localhost:8080/api/hellowill return "Hello, REST!".

This is a simple example project integrating REST with Spring Boot.

Spring Boot + GraphQL

To integrate GraphQL in Spring Boot, you can use third-party libraries (such as graphql-java and spring-graphql). Here is a simple example project:

  1. Create a Spring Boot project, either using Spring Initializer or manually.

  2. Add dependencies, making sure to pom.xmlinclude the following dependencies in the file:

<dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-spring-boot-starter</artifactId>
    <version>11.1.0</version>
</dependency>
<dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphiql-spring-boot-starter</artifactId>
    <version>11.1.0</version>
    <scope>runtime</scope>
</dependency>
  1. Create GraphQL schemas and queries such as:
# src/main/resources/graphql/schema.graphqls
type Query {
    hello: String
}
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GraphQLConfig {
    
    

    @Bean
    public GraphQLSchema schema() {
    
    
        return GraphQLSchema.newSchema()
                .query(queryType())
                .build();
    }

    @Bean
    public GraphQLQueryResolver queryType() {
    
    
        return new GraphQLQueryResolver() {
    
    
            public String hello() {
    
    
                return "Hello, GraphQL!";
            }
        };
    }
}
  1. Launch the application and access http://localhost:8080/graphiqlthe GraphQL query using the graphical interface or http://localhost:8080/graphqlsending the query via a POST request.

This is a simple Spring Boot example project integrating GraphQL, which allows you to define your own GraphQL schemas and queries and query them through HTTP endpoints.

Insert image description here

Guess you like

Origin blog.csdn.net/yangshangwei/article/details/132863341