본문 바로가기

개발일지/TIL

[ 230614 ] Java Spring에 Graphql 설정

적용 이유

친구와 사이드 프로젝트를 시작했다. 자바로 백엔드를 만들기로 했으며, Rest API 대신 Graphql을 통해 구현해 볼 것을 제안했다. 이유는 Graphql이 Rest API에 비해 언더패치와 오버패치를 방지할 수 있다는 장점이 있기 때문이었다.

Spring 적용

[ build.gradle 파일에 추가 ]

implementation 'org.springframework.boot:spring-boot-starter-graphql'

 

[ application.yml 파일에 추가 ]

graphql:
  servlet:
    enabled: true
    mapping: /graphql
    corsEnabled: true
    cors:
      allowed-origins: http://localhost:8080
      allowed-methods: GET, HEAD, POST, PATCH
    exception-handlers-enabled: true
    context-setting: PER_REQUEST_WITH_INSTRUMENTATION
    async-mode-enabled: true
  tools:
    schema-location-pattern: "**/*.graphqls"

 

[ resource/schema.graphqls 파일 추가 ]

type Query {
    userById(id: Int!): User
}

type User {
    id : Int!
    email : String
    name : String
}

 

[ UserController 추가 ]

@QueryMapping
public User userById(@Argument Long id) {
    return userService.getUser(id);
}

결과

Java Spring에 Graphql을 적용한 이후 Curl에 명령어를 통해 결과를 확인했다. 정상적으로 요청한 데이터가 내려오는 것을 확인했다.

 

참고 링크

 

Getting Started | Building a GraphQL service

GraphQL is a query language to retrieve data from a server. It is an alternative to REST, SOAP, or gRPC. In this tutorial, we will query the details for a specific book from an online store backend. This is an example request you can send to a GraphQL serv

spring.io

 

Spring for GraphQL Documentation

GraphQlHttpHandler handles GraphQL over HTTP requests and delegates to the Interception chain for request execution. There are two variants, one for Spring MVC and one for Spring WebFlux. Both handle requests asynchronously and have equivalent functionalit

docs.spring.io