GraphQL API Development

GraphQL API Development with Spring Boot

GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It provides a more efficient, powerful, and flexible alternative to REST. In this guide, we’ll cover the basics of developing a GraphQL API using Spring Boot.


Key Concepts of GraphQL

1. Schema: Defines the types and structure of data that can be queried.

2. Query: Allows clients to request specific data.

3. Mutation: Allows clients to modify data.

4. Resolvers: Functions that resolve a value for a type or field in a schema.


Setting Up the Project

1. Add Dependencies

Add the following dependencies to your `pom.xml` 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>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>


2. Define the Schema

Create a file named `schema.graphqls` in the `src/main/resources` directory:

type Query {
    getProduct(id: ID!): Product
    getAllProducts: [Product]
}

type Mutation {
    createProduct(name: String!, price: Float!): Product
    updateProduct(id: ID!, name: String, price: Float): Product
    deleteProduct(id: ID!): String
}

type Product {
    id: ID!
    name: String!
    price: Float!
}


3. Define the Entity

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private double price;

    // Getters and Setters
}


4. Create the Repository

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
}


5. Implement the Service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Product getProduct(Long id) {
        return productRepository.findById(id).orElse(null);
    }

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    public Product createProduct(String name, double price) {
        Product product = new Product();
        product.setName(name);
        product.setPrice(price);
        return productRepository.save(product);
    }

    public Product updateProduct(Long id, String name, double price) {
        Product product = productRepository.findById(id).orElse(null);

        if (product != null) {
            if (name != null) {
                product.setName(name);
            }
            if (price != 0) {
                product.setPrice(price);
            }
            return productRepository.save(product);
        }
        return null;
    }

    public String deleteProduct(Long id) {
        productRepository.deleteById(id);
        return "Product deleted";
    }
}


6. Implement GraphQL Resolvers

Query Resolver

import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ProductQueryResolver implements GraphQLQueryResolver {

    @Autowired
    private ProductService productService;

    public Product getProduct(Long id) {
        return productService.getProduct(id);
    }

    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }
}


Mutation Resolver

import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ProductMutationResolver implements GraphQLMutationResolver {
    @Autowired
    private ProductService productService;

    public Product createProduct(String name, double price) {
        return productService.createProduct(name, price);
    }

    public Product updateProduct(Long id, String name, double price) {
        return productService.updateProduct(id, name, price);
    }

    public String deleteProduct(Long id) {
        return productService.deleteProduct(id);
    }
}


Running and Testing the Application

1. Run the Application: Start your Spring Boot application.

2. Access GraphiQL: Navigate to `http://localhost:8080/graphiql` to use the GraphiQL tool for testing your GraphQL API.


Example Queries and Mutations

Query to Get All Products

{
    getAllProducts {
        id
        name
        price
    }
}


Query to Get a Single Product

{
    getProduct(id: 1) {
        id
        name
        price
    }
}


Mutation to Create a Product

mutation {
    createProduct(name: "Laptop", price: 799.99) {
        id
        name
        price
    }
}


Mutation to Update a Product

mutation {
    updateProduct(id: 1, name: "Gaming Laptop", price: 899.99) {
        id
        name
        price
    }
}


Mutation to Delete a Product

mutation {
    deleteProduct(id: 1)
}


Conclusion

GraphQL provides a flexible and efficient way to work with APIs, and Spring Boot makes it straightforward to set up and integrate. By using GraphQL with Spring Boot, you can build robust APIs that allow clients to request exactly the data they need, reducing over-fetching and under-fetching issues common with REST. This guide covered setting up a simple GraphQL API with queries and mutations, showcasing how to create a reactive and scalable backend service.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....