エムスリー Tech Talk で発表したスライドです。
GraphQL入門
View Slide
長澤 太郎● エムスリー株式会社● 日本Kotlinユーザグループ代表
もくじ1. GraphQLとは2. GraphQLを始める3. 便利なツールやサービス
1. GraphQLとは
GraphQL● Facebook発OSSであるクエリ言語○ REST APIに代わるリソース操作方法を提供○ HTTPだけでなく、gRPCやThriftの上でも動く● 必要なものだけ取得できる● 一度のリクエストで関連するものすべてを取得できる● 型システム● API定義コードがそのままドキュメントに
スキーマとクエリtype Query {hello: String}{hello}スキーマ クエリ{"data": { "hello": "Hello, world!" }}レスポンス
スキーマとクエリtype Query {hello: String}{hello}スキーマ クエリ{"data": { "hello": "Hello, world!" }}レスポンス型
スキーマとクエリtype Query {hello: String}{hello}スキーマ クエリ{"data": { "hello": "Hello, world!" }}レスポンスクエリと結果が同じ形!
{hello {content}}ユーザ定義型type Message {content: String}type Query {hello: Message}{"data": { "hello": { "content": "Hello, world!" } }}
{hello {priority}}列挙型enum Priority {HIGH, NORMAL}type Message {content: String,priority: Priority}type Query {hello: Message}{"data": {"hello": { "priority": "HIGH" } }}
{hello {priority}}列挙型enum Priority {HIGH, NORMAL}type Message {content: String,priority: Priority}type Query {hello: Message}{"data": {"hello": { "priority": "HIGH" } }}クエリと結果が同じ形!必要なフィールドを自由に選択できる!
関連するデータ(スキーマ)type User {name: String,messages: [Message]}enum Priority {HIGH, NORMAL}type Message {content: String,priority: Priorityuser: User}type Query {hello: Message}
関連するデータ(クエリ){hello {content,user {name}}{"data": {"hello": {"content": "Hello, world!","user": { "name": "Taro" }}}}
non-nulltype User {name: String!messages: [Message]!}enum Priority {HIGH, NORMAL}type Message {content: String!,priority: Priority!user: User!}type Query {hello: Message!}
コメント# ただのコメント"ドキュメント用のコメント"type Message {"内容"content: String!,"優先度"priority: Priority!"投稿者"user: User!}
スキーマ再考とミューテーション# ユーザ定義型type Message {id: Int!content: String!}# クエリtype Query {getAllMessages: [Message]!getMessage(id: Int!): Message}# ミューテーションtype Mutation {createMessage(content: String!): MessageupdateMessage(id: Int!, content: String!): Message}
ミューテーションoperationmutation {createMessage(content: "Hello, world!") {idcontent}}
ミューテーションoperationmutation {createMessage(content: "Hello, world!") {idcontent}}query {getAllMessages {idcontent}}ちなみに、クエリは指定もできるし省略もできる
データの変更を受け取る"第3のoperation"subscription {Message(filter: {mutation_in: [UPDATED, DELETED]}) {mutationnode {idcontent}previousValues {idcontent}}}
データの変更を受け取る"第3のoperation"subscription {Message(filter: {mutation_in: [UPDATED, DELETED]}) {mutationnode {idcontent}previousValues {idcontent}}}ミューテーションの種類でフィルタミューテーションの種類どういう操作があったのか変更後の値変更前の値
2. GraphQLを始める
好きな言語で実装しよう
Node + ExpressでGraphQLconst express = require('express');const graphqlHTTP = require('express-graphql');const { buildSchema } = require('graphql');const schema = buildSchema(`type Query { hello: String! }`);const root = {hello: () => 'Hello, world!';};const app = express();app.user('/graphql', graphqlHTTP({schema: schema,rootValue: root,graphiql: true}));app.listen(4000);
Node + ExpressでGraphQLconst express = require('express');const graphqlHTTP = require('express-graphql');const { buildSchema } = require('graphql');const schema = buildSchema(`type Query { hello: String! }`);const root = {hello: () => 'Hello, world!';};const app = express();app.user('/graphql', graphqlHTTP({schema: schema,rootValue: root,graphiql: true}));app.listen(4000);スキーマの定義
Node + ExpressでGraphQLconst express = require('express');const graphqlHTTP = require('express-graphql');const { buildSchema } = require('graphql');const schema = buildSchema(`type Query { hello: String! }`);const root = {hello: () => 'Hello, world!';};const app = express();app.user('/graphql', graphqlHTTP({schema: schema,rootValue: root,graphiql: true}));app.listen(4000);APIの実装
起動してクエリを実行curl http://localhost:4000/graphql\-X POST\-H 'Content-type: application/json'\-d '{"query":"{ hello }"}'{"data":{"hello":"Hello, world!"}}
起動してクエリを実行curl http://localhost:4000/graphql\-X POST\-H 'Content-type: application/json'\-d '{"query":"{ hello }"}'{"data":{"hello":"Hello, world!"}}JSON
起動してクエリを実行curl http://localhost:4000/graphql\-X POST\-H 'Content-type: application/json'\-d '{"query":"{ hello }"}'{"data":{"hello":"Hello, world!"}}GraphQL
GraphiQLconst express = require('express');const graphqlHTTP = require('express-graphql');const { buildSchema } = require('graphql');const schema = buildSchema(`type Query { hello: String! }`);const root = {hello: () => 'Hello, world!';};const app = express();app.user('/graphql', graphqlHTTP({schema: schema,rootValue: root,graphiql: true}));app.listen(4000);
GraphiQL
GraphiQLで遊んでみる● SWAPI GraphQL Wrapperhttp://graphql.org/swapi-graphql/● GitHub API v4https://developer.github.com/v4/
3. 便利なツールやサービス
GraphCMS● いわゆるHeadless CMS: API-firstなCMS● WebHookをサポート(有償版のみ)● サインアップしてコンソールに入るとチュートリアルが
モデルを定義して
データを入力して
GraphiQLで確認する
スキーマ定義ファイルをダウンロードできる
Graphcool● GraphQLバックエンドを提供するBaaS● GraphCMSのように使いやすいUI● GraphCMSより玄人向き● WebHookあり● イベントをフックできる関数をJavaScriptで定義可能
望むなら関数を定義
こんな画面も用意されている
PostGraphQL● ポスグレに作ってある既存のDBに対して、GraphQL APIを自動的につくってくれるツール
使い方$ npm install -g postgraphql$ postgraphql\-c postgres://[email protected]/db\--export-schema-graphql schema.txt
使い方$ npm install -g postgraphql$ postgraphql\-c postgres://[email protected]/db\--export-schema-graphql schema.txtDBのURLスキーマ定義ファイルの出力
すごいよ!!!!
Apollo GraphQL● GraphQLのライブラリやらを作ってるコミュニティ
Apollo GraphQL Client for Androidスキーマ定義とクエリ定義からJavaコードを自動生成してくれる!!
まとめ・雑感● GraphQLはクエリ言語でAPIが便利に● シンプルながら強力な機能● API作るときにURL考えなくてよいの助かる● ちょっとしたサービスならGraphcoolだけで自分でサーバを用意する必要なさそう● PostGraphQL、すごいけど使い道わからない● コード生成できるし言うことなしでは