01 SOFTWARE
API

GraphQL API

01 SOFTWARE 플랫폼의 GraphQL API 가이드

GraphQL API

01 SOFTWARE는 Payload CMS가 자동 생성하는 GraphQL API를 제공합니다.

GraphQL Endpoint

Production

https://api.01.software/api/graphql

Development

http://localhost:3000/api/graphql

GraphQL Playground

개발 환경에서는 GraphQL Playground를 사용할 수 있습니다:

http://localhost:3000/api/graphql-playground

GraphQL Playground는 개발 환경(NODE_ENV=development)에서만 활성화됩니다.

인증

HTTP Header

POST /api/graphql
Authorization: Bearer your_jwt_token_here
Content-Type: application/json

기본 쿼리

컬렉션 조회

query {
  Products(limit: 10, where: { status: { equals: published } }) {
    docs {
      id
      name
      price
      status
      createdAt
    }
    totalDocs
    limit
    page
    hasNextPage
  }
}

단일 항목 조회

query {
  Product(id: "product_id") {
    id
    name
    price
    description
    status
    tenant {
      id
      name
    }
  }
}

관계 데이터 포함

query {
  Post(id: "post_id") {
    id
    title
    content
    author {
      id
      email
      firstName
      lastName
    }
    categories {
      id
      name
      slug
    }
    tags {
      id
      name
    }
  }
}

Mutations

Create

mutation {
  createProduct(data: {
    name: "New Product"
    price: 15000
    status: draft
    tenant: "tenant_id"
  }) {
    id
    name
    price
    status
  }
}

Update

mutation {
  updateProduct(
    id: "product_id"
    data: {
      price: 12000
      status: published
    }
  ) {
    id
    name
    price
    status
  }
}

Delete

mutation {
  deleteProduct(id: "product_id") {
    id
    name
  }
}

복잡한 쿼리

필터링

query {
  Products(
    where: {
      and: [
        { status: { equals: published } }
        { price: { greater_than: 10000, less_than: 50000 } }
        {
          or: [
            { category: { equals: "electronics" } }
            { tags: { contains: "featured" } }
          ]
        }
      ]
    }
  ) {
    docs {
      id
      name
      price
    }
  }
}

정렬 및 페이지네이션

query {
  Posts(
    limit: 20
    page: 2
    sort: "-publishedAt"
  ) {
    docs {
      id
      title
      publishedAt
    }
    totalDocs
    page
    totalPages
    hasNextPage
    hasPrevPage
  }
}

깊은 관계 조회

query {
  Post(id: "post_id") {
    id
    title
    author {
      id
      email
      tenants {
        id
        name
        plan
      }
    }
    categories {
      id
      name
      parent {
        id
        name
      }
    }
  }
}

인증 Mutations

로그인

mutation {
  loginUser(
    email: "user@example.com"
    password: "password"
  ) {
    token
    user {
      id
      email
      role
      tenants {
        id
        name
      }
    }
    exp
  }
}

로그아웃

mutation {
  logoutUser
}

현재 사용자

query {
  meUser {
    user {
      id
      email
      role
      tenants {
        id
        name
        plan
      }
    }
  }
}

파일 업로드

GraphQL에서는 multipart/form-data를 사용하여 파일을 업로드합니다.

mutation($file: Upload!) {
  createMedia(data: {
    file: $file
    alt: "Image description"
  }) {
    id
    filename
    url
    width
    height
  }
}

Schema Introspection

전체 스키마 조회

query {
  __schema {
    types {
      name
      description
    }
  }
}

특정 타입 조회

query {
  __type(name: "Product") {
    name
    fields {
      name
      type {
        name
        kind
      }
    }
  }
}

에러 처리

에러 응답 형식

{
  "errors": [
    {
      "message": "에러 메시지",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": ["Products"],
      "extensions": {
        "code": "UNAUTHENTICATED"
      }
    }
  ],
  "data": null
}

일반적인 에러 코드

  • UNAUTHENTICATED - 인증 필요
  • FORBIDDEN - 권한 없음
  • BAD_USER_INPUT - 잘못된 입력
  • NOT_FOUND - 리소스 없음
  • INTERNAL_SERVER_ERROR - 서버 오류

GraphQL vs REST

특징GraphQLREST
요청단일 엔드포인트여러 엔드포인트
데이터필요한 필드만 선택고정된 응답
관계한 번에 가져오기여러 요청 필요
타입강력한 타입 시스템문서 의존
캐싱복잡함HTTP 캐시 활용

실전 예제

Next.js with Apollo Client

import { ApolloClient, InMemoryCache, gql } from '@apollo/client'

const client = new ApolloClient({
  uri: 'https://api.01.software/api/graphql',
  cache: new InMemoryCache(),
  headers: {
    authorization: `Bearer ${token}`
  }
})

// 쿼리 실행
const { data } = await client.query({
  query: gql`
    query GetProducts {
      Products(limit: 10) {
        docs {
          id
          name
          price
        }
      }
    }
  `
})

React with urql

import { createClient, useQuery } from 'urql'

const client = createClient({
  url: 'https://api.01.software/api/graphql',
  fetchOptions: {
    headers: {
      authorization: `Bearer ${token}`
    }
  }
})

function ProductList() {
  const [result] = useQuery({
    query: `
      query {
        Products(limit: 10) {
          docs {
            id
            name
            price
          }
        }
      }
    `
  })

  if (result.fetching) return <div>Loading...</div>
  if (result.error) return <div>Error: {result.error.message}</div>

  return (
    <ul>
      {result.data.Products.docs.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  )
}

다음 단계

On this page