0Pricing
GraphQL APIs with Spring Boot · 강의

여러 GraphQL 스키마 병합

Spring Boot 환경에서 스키마 스티칭을 구현해 여러 GraphQL 서비스를 결합하고 노출합니다.

여러 GraphQL 스키마 병합은(는) CoddyKit의 무료 GraphQL APIs with Spring Boot 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 GraphQL APIs with Spring Boot 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Unifying Your GraphQL APIs

As your application grows, you might find yourself with multiple independent GraphQL services. How do you present them as a single, cohesive API to your clients?

This lesson will guide you through implementing schema stitching in a Spring Boot application. You'll learn to combine multiple backend GraphQL schemas into one unified endpoint.

Acting as a Gateway

A GraphQL Gateway acts as a central entry point for all your client applications. Instead of clients querying multiple services directly, they query the gateway.

  • The gateway knows about all backend GraphQL services.
  • It fetches their individual schemas.
  • It combines these schemas into a single, unified schema.
  • It then routes incoming client queries to the correct backend service and aggregates the results.

Setting Up Your Spring Boot Gateway

Let's start by creating a new Spring Boot project. We'll need a few key dependencies to build our gateway:

  • spring-boot-starter-web: For web capabilities.
  • spring-graphql: To serve our combined GraphQL API.
  • graphql-java: The core library for building and manipulating GraphQL schemas.

Add these to your pom.xml or build.gradle.

Pointing to Backend Services

Our gateway needs to know where the backend GraphQL services are located. We can configure their URLs, perhaps in application.properties or through a dedicated configuration class.

For example, imagine we have a UserService and a ProductService, each with its own GraphQL endpoint:

application.properties:
  graphql.remote-services.user-service.url=http://localhost:8081/graphql
  graphql.remote-services.product-service.url=http://localhost:8082/graphql

In a real application, these would be separate Spring Boot applications.

Fetching Remote Schemas via Introspection

Before we can combine schemas, our gateway needs to discover what fields and types each backend service offers. This is done using introspection.

GraphQL provides a special introspection query that allows you to ask a GraphQL server for information about its schema. The gateway will send this query to each backend service to get their Schema Definition Language (SDL).

Fetching Schema Definition Language

Here's a simple Spring Boot component that uses WebClient to perform an introspection query and retrieve the SDL from a remote GraphQL service. This SDL will later be used to build our combined schema.

package com.coddykit.gateway;

import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Component
public class RemoteSchemaFetcher {

    private final WebClient webClient;

    public RemoteSchemaFetcher(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("").build();
    }

    // Simplified introspection query for demo
    private static final String INTROSPECTION_QUERY_BODY =
            "{\"query\":\"query { __schema { queryType { name } } }\"}";

    public Mono<String> fetchSchemaSdl(String serviceUrl) {
        return webClient.post()
                .uri(serviceUrl)
                .bodyValue(INTROSPECTION_QUERY_BODY)
                .retrieve()
                .bodyToMono(String.class)
                .map(response -> {
                    // In a real app, you'd parse the 'response' JSON
                    // to extract the actual SDL. For this example,
                    // we'll return a basic placeholder SDL.
                    return "type Query { userCount: Int }"; // Example SDL from a remote service
                });
    }

    public static void main(String[] args) {
        // This main method is for illustrative purposes only.
        // In a real Spring Boot app, this component would be managed by Spring.
        System.out.println("RemoteSchemaFetcher component simulates fetching SDL.");
        System.out.println("It uses WebClient to send an introspection query.");
        System.out.println("Actual parsing of the introspection result is omitted for brevity.");
    }
}

Combining Schema Definitions

Once we have the SDL strings from all our backend services, we need to combine them into a single GraphQLSchema object. The graphql-java library provides tools for this.

  • Use SchemaParser to parse each SDL string into a TypeDefinitionRegistry.
  • Merge these TypeDefinitionRegistry objects.
  • Use SchemaGenerator with the merged registry to create the final unified GraphQLSchema.

This combined schema is what your gateway will expose to clients.

Merging Type Definition Registries

This example demonstrates how to combine two TypeDefinitionRegistry objects into one. This is the core step in building our unified schema.

package com.coddykit.gateway;

import graphql.schema.GraphQLSchema;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;

public class SchemaCombiner {

    public GraphQLSchema combineSchemas(String userSchemaSdl, String productSchemaSdl) {
        SchemaParser schemaParser = new SchemaParser();
        
        // Parse individual SDLs into TypeDefinitionRegistry
        TypeDefinitionRegistry userRegistry = schemaParser.parse(userSchemaSdl);
        TypeDefinitionRegistry productRegistry = schemaParser.parse(productSchemaSdl);
        
        // Merge the registries
        TypeDefinitionRegistry mergedRegistry = new TypeDefinitionRegistry();
        mergedRegistry.merge(userRegistry);
        mergedRegistry.merge(productRegistry);
        
        // Generate the final GraphQLSchema
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(mergedRegistry);
    }

    public static void main(String[] args) {
        String userSdl = "type Query { user(id: ID!): User } type User { id: ID! name: String }";
        String productSdl = "type Query { product(id: ID!): Product } type Product { id: ID! name: String price: Float }";

        SchemaCombiner combiner = new SchemaCombiner();
        GraphQLSchema combinedSchema = combiner.combineSchemas(userSdl, productSdl);

        System.out.println("Combined Schema Generated Successfully!");
        // You can inspect combinedSchema.getTypeMap() to see merged types
        System.out.println("Query types in merged schema: " +
                           combinedSchema.getQueryType().getFieldDefinitions().size());
        System.out.println("Expected 2 query fields (user, product).");
    }
}

Routing Queries with DataFetchers

After combining schemas, when a client queries the gateway, the gateway needs to know which backend service should handle each field.

This is achieved using a Delegating DataFetcher. For each field in the stitched schema, this DataFetcher will:

  • Identify the original backend service for that field.
  • Construct a sub-query for that backend.
  • Send the sub-query to the correct backend service.
  • Receive the response and integrate it into the overall result.

This is the "runtime" part of stitching, where data is actually fetched.

Stitching Knowledge Check

You've learned about the key steps involved in merging multiple GraphQL schemas in a Spring Boot gateway. Which of the following is the PRIMARY reason for using a Delegating DataFetcher in a stitched GraphQL gateway?

Recap: Building a Unified API

Congratulations! You've learned the fundamental steps to merge multiple GraphQL schemas using Spring Boot:

  • Setup a Spring Boot gateway with necessary dependencies.
  • Configure remote backend GraphQL service URLs.
  • Introspect each remote service to fetch its Schema Definition Language (SDL).
  • Combine the SDLs into a single GraphQLSchema using graphql-java.
  • Implement Delegating DataFetchers to route client queries to the appropriate backend service at runtime.

This unified approach simplifies client interactions and provides a consistent API experience.

자주 묻는 질문

“여러 GraphQL 스키마 병합” 강의는 무료인가요?

네 — “여러 GraphQL 스키마 병합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 GraphQL APIs with Spring Boot 강의 전체를 잠금 해제할 수 있습니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

“여러 GraphQL 스키마 병합”에서 뭘 배우나요?

Spring Boot 환경에서 스키마 스티칭을 구현해 여러 GraphQL 서비스를 결합하고 노출합니다. 브라우저에서 직접 실행하는 실습 코드로 GraphQL APIs with Spring Boot을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

GraphQL APIs with Spring Boot을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 GraphQL APIs with Spring Boot은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“여러 GraphQL 스키마 병합” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 GraphQL APIs with Spring Boot 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 GraphQL APIs with Spring Boot 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사용자 지정 지시문 만들기
  2. 스키마 스티칭 기초
  3. 여러 GraphQL 스키마 병합
  4. 타입 확장을 사용한 스키마 모듈화
← GraphQL APIs with Spring Boot(으)로 돌아가기