GraphQL & Apollo
https://goo.gl/qYrg4q
Web Service
The Old Way

RESTful
{
"movies": [
"title": "Star Wars",
"year": 1977,
"directorId": 0,
]
}GET http://api.example.com/v1/movies
RESTful
{
"firstname": "George",
"lastname": "Lucas",
}GET http://api.example.com/v1/directors/0
Waterfall
SOAP
| HTTP Method | URL |
|---|---|
| POST | http://api.example.com/v1/movies |
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="..."
xmlns:m="...">
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetAllMovies>
<m:Genre>sf</m:Genre>
</m:GetAllMovies>
</soap:Body>
</soap:Envelope><?xml version="1.0"?>
<soap:Envelope>
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetAllMoviesResponse>
<m:Movie>
<m:Title>Star Wars</m:Title>
<m:Year>1977</m:Year>
<m:DirectorId>0</m:DirectorId>
</m:Movie>
</m:GetAllMoviesResponse>
</soap:Body>
</soap:Envelope>GraphQL

Why
GraphQL?
Fun Fact
You have already been using it
For several years

Origins

2012 - 2015
Why GraphQL?
The Big Issue

GraphQL is resolving very real problems
- Mobile client (latency)
- Multiple clients (eg. Web + iOS)
- Micro-services
- API REST which has become too complex
- Frontend ↔ Backend decoupling
REST isn't the answer

REST isn't the answer
- Ad-hoc
- Waterfall
- Size of data
- Versioning
- Fat documentations
GraphQL improves your developper experience
- Clear relationship between backends & frontends
- Less meetings & com problems
- No need to write real doc anymore
- Less time spent understanding the API
- Advanced dev tools

GraphQL
What is it exactly?
Design
- Hierarchy
- Product-oriented
- Strong typing
- Precise client requests
- Introspection
Client gets exactly what it asks for
{
movie {
title
}
}
{
"movie": {
"title": "Star Wars"
}
}
Multiple resources in one request
{
movie {
title
director {
firstname
lastname
}
}
}
MOVIES
DIRECTORS
Structuring data with Types
{
movie {
title
director {
firstname
lastname
}
}
}
type Movie {
title: String
director: Director
}
type Director {
firstname: String
lastname: String
}
Evolving without versions
type Movie {
title: String @deprecated
originalTitle: String
director: Director
releaseYear: Int
}
type Movie {
title: String
director: Director
}
Developper Experience
GraphQL
Server-side
Schema
- API Description
- Strong Typing
- Explicit usage
- Contains Types, Enums, ...
- Plus descriptions/comments!
Scalars
-
Int
-
Float
-
String
-
Boolean
-
ID
-
<your own here>
Objects
type Movie {
title: String!
releaseYear: Int
director: Person
}
type Person {
name: String!
age: Int!
}
Interfaces
interface NamedEntity {
name: String
}
type Person implements NamedEntity {
name: String
age: Int
}
Unions
type Movie {
title: String
releaseYear: Int
director: Person
}
type Person {
name: String
age: Int
}
union SearchResult = Movie | Person
Enums
enum Status {
RUMORED
IN_PRODUCTION
RELEASED
}
type Movie {
status: Status
}
Operations
schema {
# Reading
query: Query
# Editing
mutation: Mutation
# Real-time
subscription: Subscription
}
Arguments
type Query {
movie(id: ID): Movie
}
type Movie {
posterUrl(size: Int): String
}
Lists
type Query {
movies(genre: String): [Movie]
}
type Movie {
actors: [Actor]
}
Inputs
input ReviewInput {
stars: Int!
comment: String
}
type Review {
id: ID!
stars: Int!
comment: String
}
type Mutation {
addReview(movie: ID!,
review: ReviewInput): Review
}
Directives
type Movie {
title: String @deprecated
originalTitle: String
director: Director
releaseYear: Int
}
GraphQL
Client-side
Request
query {
movies(genre: "sf") {
title
director {
name
age
}
}
}
{
"data": {
"movies": [
{
"title": "Star Wars",
"director": {
"name": "George Lucas",
"age": 72
}
}
]
}
}Document
Result
Multiple Requests?
{
movies(genre: "sf") {
title
}
tvShows(genre: "sf") {
title
}
}
{
"movies": [
{
"title": "Star Wars"
}
],
"tvShows": [
{
"title": "The Expanse"
}
]
}Variables
query videos ($genre: String = "all") {
movies(genre: $genre) {
title
}
tvShows(genre: $genre) {
title
}
}
{
genre: "sf"
}
Directives
query videos ($onlyMovies: Boolean = false) {
movies @include(if: true) {
title
}
tvShows @skip(if: $onlyMovies) {
title
}
}
Fragments
query {
movies(genre: "sf") {
...movieFields
}
movies(genre: "action") {
...movieFields
}
}
fragment movieFields on Movie {
title
releaseYear
}
Inline Fragments
query {
search {
__typename
title
... on Movies {
releaseYear
}
... on TvShow {
currentSeason
}
}
}
{
"search": [
{
"__typename": "Movie",
"title": "Star Wars",
"releaseYear": 1997
},
{
"__typename": "TvShow",
"title": "The Expanse",
"currentSeason": 2
}
]
}Alias
query {
searchResults: search {
label: title
... on Movies {
year: releaseYear
}
... on TvShow {
season: currentSeason
}
}
}
{
"searchResults": [
{
"label": "Star Wars",
"year": 1997
},
{
"label": "The Expanse",
"season": 2
}
]
}Mutations
mutation addReview($movie: ID!, $review: ReviewInput) {
newReview: addReview (movie: $movie, review: $review) {
id
stars
comment
}
}
{
"newReview": {
"id": "f6gt7DA42-1F",
"stars": 5,
"comment": "This movie is awesome!"
}
}Introspection
query {
__schema {
types {
name
}
}
}
{
"__schema": {
"types": [
{
"name": "Movie"
},
{
"name": "TvShow"
}
]
}
}Meteor Development Group
meteor.io
github.com/apollographql
- GraphQL Client
- JavaScript
- Android
- iOS
- Server Tools
- express
- koa
- hapi
- restify
- AWS lambda
Apollo Optics
apollodata.com/optics

Apollo
Server-side
Design
HTTP Server
Schema
Resolvers
Connectors
type
{...}
Schema
const typeDefs = `
# General entity
interface Entity {
id: ID!
name: String!
image: String
}
# Movie
type Movie implements Entity {
id: ID!
name: String!
image: String
genre: String!
releaseYear: Int
director: Director
}
`Connectors
const collection = new DataBaseCollection()
export function getAll () {
return collection
}
export function getByGenre (genre) {
return collection.filter(i => i.genre === genre)
}
export function getById (id) {
return collection.find(i => i.id === id)
}Resolvers
const resolvers = {
Movie: {
director: (movie) => Directors.getById(movie.directorId),
},
Query: {
movies: (root, { genre }) => Movies.getByGenre(genre),
movie: (root, { id }) => Movies.getById(id),
tvShows: (root, { genre }) => TvShows.getByGenre(genre),
tvShow: (root, { id }) => TvShows.getById(id),
search: (root, { text }) => Search.search(text),
},
}Executable schema
import typeDefs from './type-defs'
import resolvers from './resolvers'
const jsSchema = makeExecutableSchema({
typeDefs,
resolvers,
})
export default jsSchemaExpress Server
import { graphqlExpress, graphiqlExpress }
from 'graphql-server-express'
import schema from './schema'
const PORT = process.env.PORT || 3000
const app = express()
// GraphQL server
app.use('/graphql', graphqlExpress({ schema }))
// GraphiQL devtool
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}))
app.listen(PORT, () => console.log(`Listening on port ${PORT}`))Done!
Apollo
Client-side
Design
Query
Mutation
Subscription (Web socket)
.gql
Observable
query

Normalized Cache
Apollo Client
import { ApolloClient, createNetworkInterface } from 'apollo-client'
// Create the apollo client
const apolloClient = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'http://localhost:3000/graphql',
transportBatching: true,
}),
connectToDevTools: true,
})
Query
import gql from 'graphql-tag'
const MOVIES_QUERY = gql`
query Movies($genre: String) {
movies (genre: $genre) {
id
name
image
genre
releaseYear
}
}`
apolloClient.query({
query: MOVIES_QUERY,
variables: { genre: "sf" },
}).then(result => {
console.log(result)
})WatchQuery
const q = apolloClient.watchQuery({
query: MOVIES_QUERY,
})
const sub = q.subscribe({
next: (result) => console.log(result),
error: (error) => console.error(error),
})
// Later...
sub.unsubscribe()Refetch
q.refetch()
q.setVariables({
genre: 'comics',
})
q.setOptions({
fetchPolicy: 'cache-only',
})Pagination: FetchMore
q.fetchMore({
variables: {
page: this.page,
pageSize,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newMovies = fetchMoreResult.paginatedMovies.movies
const hasMore = fetchMoreResult.paginatedMovies.hasMore
return {
paginatedMovies: {
// Merging the movie list
movies: [...previousResult.paginatedMovies.tags, ...newMovies],
hasMore,
},
}
},
})
Mutation
apolloClient.mutate({
mutation: gql`mutation ($label: String!) {
addTag(label: $label) {
id
label
}
}`,
variables: { label: newTag },
updateQueries: {
tagList: (previousResult, { mutationResult }) => ({
tags: [...previousResult.tags, mutationResult.data.addTag],
}),
},
optimisticResponse: {
__typename: 'Mutation',
addTag: {
__typename: 'Tag',
id: -1,
label: newTag,
},
},
}).then((data) => {
console.log(data)
}).catch((error) => {
console.error(error)
this.newTag = newTag
})Apollo + Vue
github.com/Akryum/graphql-demo

conf.vuejs.org
Thank you!
[EN] GraphQL & Apollo
By Guillaume Chau
[EN] GraphQL & Apollo
Did you use or create web services with REST or SOAP already? Don't you want something different? Discover a new way to make API, created inside Facebook labs: GraphQL. This protocol helps creating modern web services, while fulfilling today's needs: high performance mobile data, scalability, emerging usage, real-time, self-documentation... Apollo GraphQL, a community-driven project sponsored by the Meteor Development Group, allows us to effortlessly use GraphQL both server-side and client-side. The Apollo client is a serious and popular alternative to Relay, designed to work everywhere and offering some very interesting features like a smart cache system.
- 8,061
