Building GraphQL API with MongoDB, Spring Boot, Java, and Gradle
Building GraphQL API with MongoDB, Spring Boot, Java, and Gradle

In this blog post, we’ll walk through creating a GraphQL API using MongoDB, Spring Boot, Java, and Gradle. We’ll demonstrate how to query data with GraphQL, including single and multiple records, and dynamic queries. Additionally, we’ll cover testing the API using Postman and running local tests with Java.

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setting Up the Project
  4. Defining the MongoDB Collection
  5. Creating the Spring Boot Application
  6. Implementing GraphQL Queries
  7. Running and Testing the Application Locally
  8. Testing with Postman
  9. Conclusion

1. Overview

We’ll be using a sample MongoDB collection that stores application information. Our goal is to build a GraphQL API to fetch this data in various ways, leveraging the flexibility and efficiency of GraphQL.

2. Prerequisites

  • Java 11+
  • Gradle
  • MongoDB
  • Spring Boot
  • Basic understanding of GraphQL
  • Postman for API testing

3. Setting Up the Project

First, create a new Spring Boot project using the following build.gradle file:

plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.graphql-java-kickstart:graphql-spring-boot-starter:11.1.0'
    implementation 'com.graphql-java-kickstart:graphql-java-tools:11.0.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

4. Defining the MongoDB Collection

The sample MongoDB collection is structured as follows:

{
  "appId": "TechiWorks",
  "cloudAppId": "cloudAppId",
  "appComponentName": "appComponentName",
  "technologyArea": "technologyArea",
  "technologyGroup": "technologyGroup",
  "branchName": "main",
  "buildId": "70",
  "artifactVersion": "2020.01.0.70",
  "branchType": "main",
  "releaseNo": "2020.01.0",
  "releaseTag": "test_2020.01.0",
  "sharedLibraryName": "SharedLibrary",
  "notes": "Inspect test",
  "inspect": {
    "technicalDebtDuration": "0",
    "burnedBudgetCount": -1,
    "businessValueCount": -1,
    "classesCount": -1,
    "commentLinesCount": -1,
    "commentLinesPercentage": "20"
  }
}

5. Creating the Spring Boot Application

Define the MongoDB Entity

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "applications")
public class Application {
    @Id
    private String appId;
    private String cloudAppId;
    private String appComponentName;
    private String technologyArea;
    private String technologyGroup;
    private String branchName;
    private String buildId;
    private String artifactVersion;
    private String branchType;
    private String releaseNo;
    private String releaseTag;
    private String sharedLibraryName;
    private String notes;
    private Inspect inspect;

    // Getters and Setters

    public static class Inspect {
        private String technicalDebtDuration;
        private int burnedBudgetCount;
        private int businessValueCount;
        private int classesCount;
        private int commentLinesCount;
        private String commentLinesPercentage;

        // Getters and Setters
    }
}

Define the Repository

import org.springframework.data.mongodb.repository.MongoRepository;

public interface ApplicationRepository extends MongoRepository<Application, String> {
}

Create GraphQL Schema

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

type Query {
    application(appId: ID!): Application
    applications: [Application]
}

type Application {
    appId: ID!
    cloudAppId: String
    appComponentName: String
    technologyArea: String
    technologyGroup: String
    branchName: String
    buildId: String
    artifactVersion: String
    branchType: String
    releaseNo: String
    releaseTag: String
    sharedLibraryName: String
    notes: String
    inspect: Inspect
}

type Inspect {
    technicalDebtDuration: String
    burnedBudgetCount: Int
    businessValueCount: Int
    classesCount: Int
    commentLinesCount: Int
    commentLinesPercentage: String
}

Implement GraphQL Query Resolver

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

import java.util.List;

@Component
public class ApplicationQueryResolver implements GraphQLQueryResolver {

    @Autowired
    private ApplicationRepository applicationRepository;

    public Application getApplication(String appId) {
        return applicationRepository.findById(appId).orElse(null);
    }

    public List<Application> getApplications() {
        return applicationRepository.findAll();
    }
}

6. Running and Testing the Application Locally

Running the Application

To run the Spring Boot application, execute the following command in your terminal from the root directory of your project:

./gradlew bootRun

The application will start on http://localhost:8080.

7. Testing with Postman

Single Record Query

  1. Open Postman and create a new POST request.
  2. Enter the URL: http://localhost:8080/graphql.
  3. Set Headers:
    • Key: Content-Type
    • Value: application/json
  4. Enter the Body: { "query": "{ application(appId: \"TechiWorks\") { appId cloudAppId appComponentName } }" }
  5. Send the Request: Click on the Send button to see the response from the GraphQL service.

Multiple Records Query

  1. Enter the Body: { "query": "{ applications { appId cloudAppId appComponentName } }" }
  2. Send the Request: Click on the Send button to see the response.

Dynamic Query with Criteria

  1. Query with appId,artifactVersion and appComponentName : { "query": "{ applications { appId artifactVersion appComponentName } }" }
  2. Query with appId, artifactVersion, branchType and appComponentName { "query": "{ applications { appId artifactVersion branchType appComponentName } }" }
  3. Query with appId, artifactVersion, branchType, and inspect.commentLinesPercentage: { "query": "{ applications { appId artifactVersion branchType inspect { commentLinesPercentage } } }" }

8. Conclusion

By following this guide, you have successfully built a GraphQL API using MongoDB, Spring Boot, Java, and Gradle. You learned how to transform an existing data structure into GraphQL types, implement query resolvers, and test your API using Postman. This setup allows for flexible data querying and efficient client-server communication, enhancing your application’s performance and scalability.

With this knowledge, you’re now equipped to leverage GraphQL’s powerful querying capabilities in your Spring Boot applications, providing more dynamic and efficient APIs for your users.

Leave a Reply

Your email address will not be published. Required fields are marked *