GraphQL API 実装の照会

APIkit for GraphQL を使用してデータを照会する GraphQL サービスの実装例を示します。

これらの例を実行する前に、APIkit for GraphQL アプリケーションサンプルをダウンロードして実行し、テスト用のサンプルデータセットをメモリに読み込んでください。HTTP POST 要求で送信されるクエリの形式は、 こちら​を参照してください。

サンプルアプリケーションは、次の GraphQL API をベースにしています。

type Post {
    id: ID!
    user: User
    title: String
    body: String
    comments: [Comment]
}

type Comment {
    id: ID!
    user: User
    post: Post
    body: String
    replies: [Comment]
}

type User {
    id: ID!
    name: String
    username: String
    email: String
    phone: String
    website: String
    address: Address
}

type Address {
    id: ID!
    street: String
    city: String
    zipcode: String
    latitude: Float
    longitude: Float
}

input AddressInput {
    street: String
    city: String
    zipcode: String
    latitude: Float
    longitude: Float
}

input UserInput {
    name: String
    username: String
    email: String
    phone: String
    website: String
    address: AddressInput
}

type Query {
    # Looks for a user by ID
    getUser(id: ID!): User
    # Looks for a post by ID
    getPost(id: ID!): Post
    # Returns the list of all users
    allUsers: [User]
    # Returns the list of all posts
    allPosts: [Post]
}

type Mutation {
    # Creates a new user
    createUser(user: UserInput!): User!
    # Creates a new post
    createPost(userId: ID!, title: String!, body: String!): Post!
    # Adds a comment to a post
    postComment(userId: ID!, postId: ID!, body: String!): Comment!
    # Adds a reply to a comment
    replyToComment(commentId: ID!, userId: ID!, body: String!): Comment!
}

要求クエリの例

次の例では、​Query​ 型はサービスが公開するクエリのリストを定義します。

...
type Query {
    # Looks for a user by ID
    getUser(id: ID!): User
    # Looks for a post by ID
    getPost(id: ID!): Post
    # Returns the list of all users
    allUsers: [User]
    # Returns the list of all posts
    allPosts: [Post]
}
...

すべての投稿の取得

このユースケースでは、既存の各投稿のデータをシンプルに要求します。

クエリの作成

{
   allPosts {
       id
       title
       body
   }
}

要求のトリガー

curl --location --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"{allPosts{id title body}}","variables":{}}'

応答の取得

{
   "data": {
       "allPosts": [
           {
               "id": "88",
               "title": "tellus nisi eu orci mauris lacinia sapien quis libero",
               "body": "Praesent id massa id nisl venenatis lacinia. Aenean sit amet justo. Morbi ut odio. Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo. In blandit ultrices enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin interdum mauris non ligula pellentesque ultrices. Phasellus id sapien in sapien iaculis congue. Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl."
           },
           {
               "id": "89",
               "title": "mauris lacinia sapien quis libero",
               "body": "Sed ante. Vivamus tortor. Duis mattis egestas metus. Aenean fermentum. Donec ut mauris eget massa tempor convallis. Nulla neque libero, convallis eget, eleifend luctus, ultricies eu, nibh. Quisque id justo sit amet sapien dignissim vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla dapibus dolor vel est. Donec odio justo, sollicitudin ut, suscipit a, feugiat et, eros."
           },
           ...
           {
            "id": "87",
               "title": "nam tristique",
               "body": "Proin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem. Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit. Donec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque."
           }
       ]
   }
}

データローダーによるすべてのユーザーの取得

このクエリは、すべてのユーザーのデータ (アドレス情報など) を要求します。この例では、データローダーを使用して 1 つの要求で各ユーザーのアドレスを取得しています。

クエリの作成

{
   allUsers {
       name
       email
       website
       address {
           street
           city
           zipcode
       }
   }
}

要求のトリガー

curl --location --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"{allUsers{name email website address{street city zipcode}}}","variables":{}}'

応答の取得

{
   "data": {
       "allUsers": [
           {
               "name": "Rollin Sebley",
               "email": "rsebley2f@ucsd.edu",
               "website": "homestead.com",
               "address": {
                   "street": "432 Myrtle Trail",
                   "city": "Pau",
                   "zipcode": "64029 CEDEX 9"
               }
           },
           {
               "name": "Bonny Madgewick",
               "email": "bmadgewick2g@mozilla.com",
               "website": "utexas.edu",
               "address": {
                   "street": "5 David Terrace",
                   "city": "Oelaba",
                   "zipcode": null
               }
           },
           ...
           {
               "name": "Gretal Titmuss",
               "email": "gtitmuss2e@soup.io",
               "website": "creativecommons.org",
               "address": {
                   "street": "3201 Gale Place",
                   "city": "Bolo",
                   "zipcode": "4201"
               }
           }
       ]
   }
}

ID での投稿の取得

このクエリ例では、投稿コメントやユーザー名などの投稿データを ID で要求しています。

クエリの作成

{
   getPost(id: 10) {
       id
       user {
           username
       }
       title
       body
       comments {
           user {
               username
           }
           body
           replies {
               body
           }
       }
   }
}

要求のトリガー

curl --location --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"{getPost(id:10){id user{username}title body comments{user{username}body replies{body}}}}","variables":{}}'

応答の取得

{
   "data": {
       "getPost": {
           "id": "10",
           "user": {
               "username": "bdearelli"
           },
           "title": "id luctus nec molestie sed justo pellentesque viverra pede ac",
           "body": "Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti. Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
           "comments": [
               {
                   "user": {
                       "username": "cwalesby1p"
                   },
                   "body": "Praesent blandit. Nam nulla. Integer pede justo, lacinia eget, tincidunt eget, tempus vel, pede. Morbi porttitor lorem id ligula. Suspendisse ornare consequat lectus. In est risus, auctor sed, tristique in, tempus sit amet, sem.",
                   "replies": []
               },
               {
                   "user": {
                       "username": "rricci2d"
                   },
                   "body": "Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui.",
                   "replies": []
               }
           ]
       }
   }
}

要求変異の例

Mutation​ 型は、サービスが有効化する変異のリストを定義します。

...
type Mutation {
    # Creates a new user
    createUser(user: UserInput!): User!
    # Creates a new post
    createPost(userId: ID!, title: String!, body: String!): Post!
    # Adds a comment to a post
    postComment(userId: ID!, postId: ID!, body: String!): Comment!
    # Adds a reply to a comment
    replyToComment(commentId: ID!, userId: ID!, body: String!): Comment!
}
...

新規投稿の作成

この例では、新しい投稿を作成して、投稿に関するいくつかの情報を要求します。

クエリの作成

mutation CreatePost($userId: ID!, $title: String!, $body: String!) {
   createPost(userId: $userId,title: $title,body: $body) {
       id
       user {
           username
       }
       title
       body
       comments {
           body
       }
   }
}

変数の作成

{
   "userId": 42,
   "title": "GraphQL by example",
   "body": "Let's talk about GraphQL"
}

要求のトリガー

curl --location --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation CreatePost($userId:ID!,$title:String!,$body:String!){createPost(userId:$userId,title:$title,body:$body){id user{username}title body comments{body}}}","variables":{"userId":42,"title":"GraphQL by example","body":"Let'\''s talk about GraphQL"}}'

応答の取得

{
   "data": {
       "createPost": {
           "id": "101",
           "user": {
               "username": "tblackmore15"
           },
           "title": "GraphQL by example",
           "body": "Let's talk about GraphQL",
           "comments": []
       }
   }
}

新規投稿へのコメントの追加

この例では、前の手順で作成した投稿への返信としてコメントを投稿します。また、作成したコメントの本文と、新しいコメントが含まれていることを確認するために元の投稿をコメントリスト付きで返すようにサービスに要求します。

クエリの作成

mutation PostComment($userId: ID!, $postId: ID!, $body: String!) {
   postComment(userId: $userId, postId: $postId, body: $body) {
       id
       body
       post {
           id
           title
           comments {
               id
               user {
                   username
               }
               body
           }
       }
   }
}

変数の作成

{
   "userId": 34,
   "postId": 101,
   "body": "Nice post! Thanks for sharing! It's just what I was looking for"
}

要求のトリガー

curl --location --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation PostComment($userId:ID!,$postId:ID!,$body:String!){postComment(userId:$userId,postId:$postId,body:$body){id body post{id title comments{id user{username}body}}}}","variables":{"userId":34,"postId":101,"body":"Nice post! Thanks for sharing! It'\''s just what I was looking for"}}'

応答の取得

{
   "data": {
       "postComment": {
           "id": "201",
           "body": "Nice post! Thanks for sharing! It's just what I was looking for",
           "post": {
               "id": "101",
               "title": "GraphQL by example",
               "comments": [
                   {
                       "id": "201",
                       "user": {
                           "username": "ekosex"
                       },
                       "body": "Nice post! Thanks for sharing! It's just what I was looking for"
                   }
               ]
           }
       }
   }
}

投稿の新規コメントへの返信

この要求例では、前の手順で投稿したコメントへの返信を応答として返します。クエリでは、新規返信に加えて投稿のすべての情報を返すようにサービスに要求します。

クエリの作成

mutation ReplyToComment($commentId: ID!, $userId: ID!, $body: String!) {
   replyToComment(commentId: $commentId, userId: $userId, body: $body) {
       id
       body
       post {
           id
           title
           comments {
               id
               body
               replies {
                   id
                   user {
                       username
                   }
                   body
               }
           }
       }
   }
}

変数の作成

{
   "commentId": 201,
   "userId": 42,
   "body": "Thank you!"
}

要求のトリガー

curl --location --request POST 'http://localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation ReplyToComment($commentId:ID!,$userId:ID!,$body:String!){replyToComment(commentId:$commentId,userId:$userId,body:$body){id body post{id title comments{id body replies{id user{username}body}}}}}","variables":{"commentId":201,"userId":42,"body":"Thank you!"}}'

応答の取得

{
   "data": {
       "replyToComment": {
           "id": "202",
           "body": "Thank you!",
           "post": {
               "id": "101",
               "title": "GraphQL by example",
               "comments": [
                   {
                       "id": "201",
                       "body": "Nice post! Thanks for sharing! It's just what I was looking for",
                       "replies": [
                           {
                               "id": "202",
                               "user": {
                                   "username": "tblackmore15"
                               },
                               "body": "Thank you!"
                           }
                       ]
                   }
               ]
           }
       }
   }
}