GraphQL (with Apollo GraphQL)
들어가며
- 데이터 질의 언어 중 하나인 GraphQL에 대해 정리해본다.

GraphQL
개념
- Meta(Facebook)가 개발한 데이터 질의 언어(Data Query Language)
- 클라이언트와 서버 간 데이터 요청 및 관리를 더 효율적으로 처리하기 위해 설계된 기술
- REST API의 대안으로 주목받고 있으며, 데이터 요청에 있어 더 유연하고 효율적인 접근 방식을 제공한다.
- 클라이언트가 원하는 데이터만 정확히 요청할 수 있도록 지원한다.
- 메타(Meta)의 서비스, Pinterest, Airbnb, AWS, Microsoft 등 많은 곳에서 이용하고 있다.
GraphQL | A query language for your API
Evolve your API without versions Add new fields and types to your GraphQL API without impacting existing queries. Aging fields can be deprecated and hidden from tools. By using a single evolving version, GraphQL APIs give apps continuous access to new feat
graphql.org
서버/클라이언트 구축 라이브러리
- GraphQL 서버와 클라이언트를 구축하기 위해 여러가지 라이브러리를 사용할 수 있다.
라이브러리 | |
서버 | Apollo, Express-GraphQL, GraphQL Yoga, Relay |
클라이언트 | Apollo, urql, Relay, Axios + Vanilla JS, graphql-request |
특징
클라이언트 중심 데이터 요청
- 클라이언트가 필요한 데이터의 형태와 구조를 직접 정의하여 요청할 수 있다.
- REST API의 고정된 엔드포인트 구조와는 다르다.
단일 엔드포엔트
- GraphQL 서버는 단일 엔드포인트를 통해 모든 요청을 처리한다.
- 클라이언트는 단일 엔드포인트를 통해 다양한 데이터 요청을 보낼 수 있다.
계층적 데이터 요청
- GraphQL을 이용하여 데이터의 관계를 계층적으로 표현할 수 있다.
- 한 번의 요청으로 여러 리소스를 동시에 조회할 수 있다.
타입 시스템(Type System)
- 클라이언트와 서버 간의 데이터 구조를 명확히 정의한다.
- 타입 시스템은 스키마(Schema)를 통해 관리된다.
오버 페칭 및 언더 페칭 해결
- 클라이언트가 원하는 데이터만 선택적으로 요청할 수 있어 불필요한 데이터 전송(오버페칭)이나 필요한 데이터가 부족한 문제(언더페칭)를 방지할 수 있다.
구성 요소
- GraphQL의 주요 구성 요소를 살펴보자.
① 스키마(Schema)
- GraphQL 서버는 스키마를 통해 API의 데이터 구조를 정의한다.
- 스키마에는 데이터 타입(Data Type), 쿼리(Query), 변형(Mutation), 구독(Subscription) 등이 포함된다.
// 데이터 타입 type User { id: ID! name: String! email: String! } // 쿼리 type Query { getUser(id: ID!): User } // 변형 type Mutation { updateUser(id: ID!, name: String!): User }
② 쿼리(Query)
- 클라이언트가 서버에 데이터를 요청하는 방식
- 필요한 필드만 선택적으로 요청할 수 있다.
// id가 '1'인 User의 id, name, email 값 요청하기 query { getUser(id: "1") { id name email } }
③ 변형(Mutation)
- 데이터를 생성(Create), 수정(Update), 삭제(Delete)하기 위해 사용된다.
// id가 '1'인 User의 이름을 'John Doe'로 변경하기 mutation { updateUser(id: "1", name: "John Doe") { id name } }
인자(Argument)
- 필드에 전달되는 파라미터(Parameter)로, 결과를 필터링하거나 수정하기 위해 사용된다.
- 다음과 같이
limit: 10
인자를 사용하여 10개의 항목만 요청할 수 있다.
query { posts(limit: 10) { title } }
④ 구독(Subscription)
- 실시간 데이터의 업데이트를 처리하는 데 사용된다.
- 예) 채팅 앱에서 새 메시지를 구독하는 경우
// 새로운 메시지가 추가될 경우, id, content, userName을 클라이언트에 전송 subscription { messageAdded { id content user { name } } }
⇒ 클라이언트는 서버에 연결을 유지하여 특정 이벤트를 구독(실시간으로 수신)한다.
GraphQL vs. REST API
특징 | REST API | GraphQL |
엔드포인트 | 여러 엔드포인트 사용 | 단일 엔드포인트 사용 |
데이터 요청 방식 | 고정된 리소스 구조 | 필요한 데이터만 유연하게 요청 |
오버 페칭 / 언더 페칭 문제 | 있음. | 없음. |
실시간 업데이트 | 제한적 | 지원 가능 (구독(Subscription)) |

연습해보기
- 아래의 사이트에서 GraphQL 사용법을 연습해볼 수 있다.
8 Free to Use GraphQL APIs for Your Projects and Demos | Apollo GraphQL Blog
Unlock microservices potential with Apollo GraphQL. Seamlessly integrate APIs, manage data, and enhance performance. Explore Apollo's innovative solutions.
www.apollographql.com
Explorer - GitHub Docs
For more information about how to use the explorer, see Using the Explorer.
docs-internal.github.com
Apollo GraphQL
개념
- GraphQL을 더 쉽고 효율적으로 사용할 수 있도록 도와주는 오픈소스 라이브러리 및 도구 모음
- GraphQL 서버, 클라이언트, 캐싱 등 여러 기능을 제공한다.
Streamlining APIs, Databases, & Microservices | Apollo GraphQL
Unlock microservices potential with Apollo GraphQL. Seamlessly integrate APIs, manage data, and enhance performance. Explore Apollo's innovative solutions.
www.apollographql.com
장점
- 복잡한 GraphQL 서버와 클라이언트를 빠르고 간단하게 구축 할 수 있다.
- 클라이언트 측 데이터 캐싱으로 데이터에 빠르게 접근할 수 있다.
- 구독(Subscription)으로 실시간 데이터 업데이트를 처리할 수 있다.
- 다양한 백엔드 및 프론트엔드 기술과 통합 가능하다.
Apollo Server
개념
- GraphQL API를 구축하기 위한 서버 라이브러리
- Node.js 환경에서 주로 사용된다.
특징
- 스키마 정의 및 리졸버(Resolver) 작성 지원
- REST API와 통합 가능
- 실시간 구독(Subscription) 지원
- 편리한 데이터 소스(Data Sources) 관리
설치
$ npm install apollo-server graphql # yarn add apollo-server graphql
사용 예시 코드
const { ApolloServer, gql } = require('apollo-server'); // 스키마 정의 const typeDefs = gql` type Query { hello: String } `; // 리졸버 정의 const resolvers = { Query: { hello: () => 'Hello, world!', }, }; // Apollo 서버 생성 const server = new ApolloServer({ typeDefs, resolvers }); // 서버 실행 server.listen().then(({ url }) => { console.log(`🚀 Server ready at ${url}`); });
Apollo Client
개념
- GraphQL API를 사용하기 위한 클라이언트 라이브러리
- React, Vue, Angular와 같은 프론트엔드 프레임워크에서 주로 사용한다.
특징
- GraphQL 쿼리(Query)와 변형(Mutation) 관리
- 데이터 캐싱 기능 제공
- 실시간 구독(Subscription) 처리
- 리액트(React)와의 강력한 통합 기능
- Apollo Provider, Hooks 지원
설치
$ npm install @apollo/client graphql # yarn add @apollo/client graphql
사용 예시 코드
- 리액트(React)에서의 사용 예시 코드
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client'; // Apollo Client 생성 const client = new ApolloClient({ uri: 'http://localhost:4000', // GraphQL 서버 URL cache: new InMemoryCache(), }); // GraphQL Query const GET_HELLO = gql` query { hello } `; function Hello() { const { loading, error, data } = useQuery(GET_HELLO); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return <h1>{data.hello}</h1>; } function App() { return ( <ApolloProvider client={client}> <Hello /> </ApolloProvider> ); } export default App;
GraphQL API를 구축하려면 Apollo Server를, 클라이언트에서 데이터를 요청하려면 Apollo Client를 사용한다.
참고 사이트
What is GraphQL?
Learn about the journey of a GraphQL operation and the components that make up a GraphQL server...
www.apollographql.com
GraphQL | A query language for your API
Evolve your API without versions Add new fields and types to your GraphQL API without impacting existing queries. Aging fields can be deprecated and hidden from tools. By using a single evolving version, GraphQL APIs give apps continuous access to new feat
graphql.org
Documentation
Hover over each section to learn about what it covers and which teams find it most useful.
www.apollographql.com
GraphQL
Graph Q uery L anguage: GraphQL GraphQL은 메타 플랫폼 구 페이스북 에서 개발
namu.wiki
'Study > Network' 카테고리의 다른 글
[Network] 400 오류와 401 오류의 차이점 (0) | 2024.11.13 |
---|---|
[Network] API(Application Programming Interface) (0) | 2023.11.15 |
[Network] 미들웨어(Middleware) (0) | 2023.11.09 |
[Network] HTTP 응답 상태 코드(Response Status Code) (0) | 2023.11.08 |
[Network] HTTP 요청(Request) 메서드의 종류 (0) | 2023.11.08 |