🌐 Web Development

GraphQL

GraphQL (Graph Query Language)

GraphQL is an API query language developed by Facebook that lets clients request exactly the data they need. It solves REST's over-fetching and under-fetching problems and provides a powerful type system and introspection.

πŸ“– Detailed Explanation

GraphQL is an API query language and runtime that was developed internally at Facebook in 2012 and released as open source in 2015. It was created for optimized data fetching in the slow network environments of mobile apps, and it resolves the chronic problems of REST APIs. It is currently adopted by large services such as GitHub, Shopify, and Twitter.

The core concept is the schema. When types and fields are defined in SDL (Schema Definition Language), the client requests only the fields it wants within that schema. Over-fetching (receiving unnecessary data) and under-fetching (having to make multiple requests) disappear, and network efficiency improves significantly.

There are three operation types: Query (read), Mutation (write/update/delete), and Subscription (real-time subscription). Query handles data retrieval, Mutation handles data changes, and Subscription handles real-time updates via WebSocket. All operations are handled through a single endpoint (/graphql).

Introspection is a powerful developer experience feature of GraphQL. Because the schema itself can be queried, tools such as GraphiQL and Apollo Sandbox provide autocomplete, documentation, and query testing. The contract between frontend and backend becomes clear, making collaboration easier.

πŸ’» Code Example

# GraphQL μŠ€ν‚€λ§ˆ μ •μ˜ (SDL)
type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
  createdAt: DateTime!
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
  published: Boolean!
}

type Query {
  user(id: ID!): User
  users(limit: Int, offset: Int): [User!]!
  post(id: ID!): Post
}

type Mutation {
  createUser(name: String!, email: String!): User!
  createPost(title: String!, content: String!, authorId: ID!): Post!
  publishPost(id: ID!): Post!
}

# ν΄λΌμ΄μ–ΈνŠΈ 쿼리 μ˜ˆμ‹œ - ν•„μš”ν•œ ν•„λ“œλ§Œ μš”μ²­
query GetUserWithPosts($userId: ID!) {
  user(id: $userId) {
    id
    name
    posts {
      id
      title
      published
    }
  }
}

# Mutation μ˜ˆμ‹œ
mutation CreateNewPost($input: CreatePostInput!) {
  createPost(input: $input) {
    id
    title
    author {
      name
    }
  }
}

// JavaScript ν΄λΌμ΄μ–ΈνŠΈ (Apollo Client)
import { gql, useQuery, useMutation } from '@apollo/client';

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
      posts {
        id
        title
      }
    }
  }
`;

function UserProfile({ userId }) {
  const { loading, error, data } = useQuery(GET_USER, {
    variables: { id: userId },
  });

  if (loading) return <p>λ‘œλ”© 쀑...</p>;
  if (error) return <p>μ—λŸ¬: {error.message}</p>;

  return (
    <div>
      <h1>{data.user.name}</h1>
      <ul>
        {data.user.posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

πŸ—£οΈ Examples of Practical Conversations

πŸ‘¨β€πŸ’» Frontend Developer
"I only need to show the 3 most recent posts on the user profile, but the REST API returns user info and posts separately, so I have to make 2 calls. The post response also has way too many fields I don't need."
πŸ‘©β€πŸ’» Backend developer
"If we switch to GraphQL, we can fetch the user and posts together in a single request. We request only 3 with the limit argument and specify only the fields we need, so the response gets cleaner too. Once the schema is defined, the frontend just changes the query as needed."
πŸ‘¨β€πŸ’Ό Technical interviewer
"How do you solve the N+1 problem in GraphQL?"
πŸ‘¨β€πŸ’» Candidate
"We use the DataLoader pattern. Instead of individual DB queries in each resolver, DataLoader collects the requests into a batch and processes them all at once. For example, when fetching 10 authors, it is solved with a single WHERE id IN (...) instead of 10 queries."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More