GraphQL
Practical usage with
GraphQL: an
application query
language
GraphQL History
• 2012 - GraphQL created at Facebook
• 2015 - GraphQL is open sourced, Relay Classic is open
sourced (React tools)
• 2016 - GitHub announces GraphQL API, New GraphQL
website graphql.org, First GraphQL Summit
(apollographql.com)
• 2017 - Relay Modern 1.0, Apollo Client 2.0, Angular v5
GraphQL vs Rest
• extra roundtrip with REST API, endpoint for each
kind of data, keep a huge number of endpoints
and maintain them.
• Documentation that needs to be updated, won’t
be updated
• Support Different versions (/v1, /v2 etc)
latest GET /latest(.:format) list#
category_latest GET /c/:category/l/latest(.:format) list#
category_none_latest GET /c/:category/none/l/latest(.:format) list#
parent_category_category_latest GET /c/:parent_category/:category/l/latest(.:format) list#
unread GET /unread(.:format) list#
category_unread GET /c/:category/l/unread(.:format) list#
category_none_unread GET /c/:category/none/l/unread(.:format) list#
parent_category_category_unread GET /c/:parent_category/:category/l/unread(.:format) list#
new GET /new(.:format) list#
category_new GET /c/:category/l/new(.:format) list#
category_none_new GET /c/:category/none/l/new(.:format) list#
parent_category_category_new GET /c/:parent_category/:category/l/new(.:format) list#
read GET /read(.:format) list#
category_read GET /c/:category/l/read(.:format) list#
category_none_read GET /c/:category/none/l/read(.:format) list#
parent_category_category_read GET /c/:parent_category/:category/l/read(.:format) list#
posted GET /posted(.:format) list#
category_posted GET /c/:category/l/posted(.:format) list#
category_none_posted GET /c/:category/none/l/posted(.:format) list#
parent_category_category_posted GET /c/:parent_category/:category/l/posted(.:format) list#
bookmarks GET /bookmarks(.:format) list#
category_bookmarks GET /c/:category/l/bookmarks(.:format) list#
category_none_bookmarks GET /c/:category/none/l/bookmarks(.:format) list#
parent_category_category_bookmarks GET /c/:parent_category/:category/l/bookmarks(.:format) list#
B A C K E N D F O R F R O N T -
Exploding number of
specific “feature” APIs
Generic APIs
that over-fetch data
1. With graphQL you
only get data which
you exactly need,
not more, not less
2. Multiple resources
in single request
3. Validation and
autocompletion
GraphQL: No more Over- and Underfetching
GraphQL Use Cases
• GraphQL server with
a connected
database

• GraphQL layer that
integrates existing
systems
Hybrid approach with connected database
and integration of existing system
GraphQL SDL - Schema
Definition Language
type Project {
id: ID! //"!" denotes a required field
name: String
tagline: String
contributors: [User]
}
type User {
id: ID!
name: String
age: Int
}
A schema is a collection of types, interfaces, enums, and unions that make up your API’s data model
Schema is strongly typed and self-documenting
Core Concepts: Type System
• Scalar Types: Int, Float, String, Boolean, ID
• Object Types: User, Project
• Entry points: Query, Mutation, Subscription
type Query {
projects: [Project]
project(id: ID!): Project
user(id: ID!): User
users: [User]
}
type Mutation {
addUser(user: UserInput): User
addProject(name: String!): Project
}
Schema Types
• Scalar types
• Enumeration types

• Interfaces
• Union types
• Input types
• Fragments
http://graphql.org/learn/schema/
scalar Date
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
type Human implements Character { ….. }
union SearchResult = Human | Droid | Starship
Resolvers
A function on a GraphQL server that's responsible for
fetching the data for a single field, takes 4 arguments:
Glue between schema types and actual data
1. parent : The result of the previous resolver call (more info).
2. args : The arguments of the resolver’s field.
3. context : A custom object each resolver can read from/write to
4. info : An AST representation of the query or mutation.
Entry Points
Execution Flow
Graphql Server Libraries
• express-graphql: Bare minimum server for express
• apollo-server: Works with multiply web
frameworks but requires some of boilerplate
• graphql-yoga: Simple setup, lots of tooling
support e.g. realtime subscriptions, Graphql
Playground. Uses apollo under hood.
GraphQL-JS Hello-World
var express = require('express');
var express_graphql = require('express-graphql');
var { buildSchema } = require('graphql');
// GraphQL schema
var schema = buildSchema(`
type Query {
message: String
}
`);
// Root resolver
var root = {
message: () => 'Hello World!'
};
// Create an express server and a GraphQL endpoint
var app = express();
app.use('/graphql', express_graphql({
schema: schema,
rootValue: root,
graphiql: true
}));
app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
What is Apollo?
Client-side tooling
● Apollo Client
● Apollo iOS
● Apollo Android
● Dev tools
● apollo-codegen
● eslint-plugin-graphq
Server-side tooling
● Apollo Server
● Graphql-tools

○ Schema creation
○ Mocking
○ Stitching
● Apollo Optics
A set of projects designed to leverage GraphQL and work together
to create a great workflow.
Apollo Graphql Server
const express = require('express');
const bodyParser = require('body-parser');
const { graphqlExpress, graphiqlExpress } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');
// Some fake data
const books = [ … ]
// The GraphQL schema in string form
const typeDefs = `
type Query { books: [Book] }
type Book { title: String, author: String }
`;
// The resolvers
const resolvers = {
Query: { books: () => books },
};
// Put together a schema
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// Initialize the app
const app = express();
// The GraphQL endpoint
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
// GraphiQL, a visual editor for queries
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
// Start the server
app.listen(3000, () => {
console.log('Go to http://localhost:3000/graphiql to run queries!');
});
A GraphQL API in just a few lines of code link
Bootstrap GraphQL Server
$ npm install -g graphql-cli
$ graphql create your-cool-project --boilerplate typescript-advanced
graphql-yoga +
• GraphQL spec-compliant
• File upload
• GraphQL Subscriptions
• TypeScript typings
• GraphQL Playground
• Extensible via Express middlewares
• Apollo Tracing
• Hosting (local or cloud)
• control over your database schema
• Extra stuff like authentication, email, etc
GraphQL server architecture
with Prisma
Database
GraphQL web server
Prisma service
Prisma is a GraphQL database proxy turning your database into a GraphQL API
<Demo graphql playground>
Main Module
Authentification
• express-jwt middleware + auth0
• pass encoded user in global context (which is available for all resolvers)
• use @UseGuard to secure query or mutations (works like for routes)
NestJS-GraphQL Module
https://docs.nestjs.com/graphql/quick-start
Graphql Schema Merging
Nest Project Structure
Apollo Client v2.0
• construct and send HTTP request (e.g. with fetch in Javascript)
• receive and parse server response
• store data locally (either simply in memory or persistent)
npm install apollo-client apollo-angular apollo-cache-inmemory apollo-angular-link-http graphql graphql-tag --save
Apollo Client Setup
Graphql JS IDE Plugin
• Schema setup
• completion
• error highlighting
• schema viewer, structure view
• documentation
Need to create
graphql.config.json
https://github.com/jimkyndemeyer/js-graphql-intellij-plugin
Code Generation
• Apollo-codegen
apollo-codegen introspect-schema /
http://localhost:8080/graphql /
—output ./src/app/graphql/schema.json
apollo-codegen generate ./src/app/**/*.ts /
—tag-name gql --schema ./src/app/graphql/
schema.json /
—target typescript /
—output ./src/app/graphql/operation-result-
types.ts
Querying Data
Apollo DevTools
GraphQL Replaces Redux
Conclusions
• GraphQL APIs have a strongly typed schema
• No more overfetching and underfetching
• GraphQL enables rapid product development
• Composing GraphQL APIs
• Rich open-source ecosystem and an amazing community
Useful Links
• https://blog.graph.cool/graphql-server-basics-the-schema-ac5e2950214e
• https://medium.com/@weblab_tech/graphql-everything-you-need-to-know-58756ff253d8
• https://blog.graph.cool/introducing-prisma-1ff423fd629e
• https://blog.graph.cool/how-to-wrap-a-rest-api-with-graphql-8bf3fb17547d
• https://blog.graph.cool/tutorial-how-to-build-a-graphql-server-with-graphql-yoga-6da86f346e68
• https://www.howtographql.com/graphql-js/1-getting-started/
• https://www.howtographql.com/advanced/0-clients/
• https://github.com/howtographql/angular-apollo
• https://github.com/gsans/todo-apollo-v2

Graphql usage

  • 1.
  • 2.
  • 4.
    GraphQL History • 2012- GraphQL created at Facebook • 2015 - GraphQL is open sourced, Relay Classic is open sourced (React tools) • 2016 - GitHub announces GraphQL API, New GraphQL website graphql.org, First GraphQL Summit (apollographql.com) • 2017 - Relay Modern 1.0, Apollo Client 2.0, Angular v5
  • 5.
    GraphQL vs Rest •extra roundtrip with REST API, endpoint for each kind of data, keep a huge number of endpoints and maintain them. • Documentation that needs to be updated, won’t be updated • Support Different versions (/v1, /v2 etc)
  • 6.
    latest GET /latest(.:format)list# category_latest GET /c/:category/l/latest(.:format) list# category_none_latest GET /c/:category/none/l/latest(.:format) list# parent_category_category_latest GET /c/:parent_category/:category/l/latest(.:format) list# unread GET /unread(.:format) list# category_unread GET /c/:category/l/unread(.:format) list# category_none_unread GET /c/:category/none/l/unread(.:format) list# parent_category_category_unread GET /c/:parent_category/:category/l/unread(.:format) list# new GET /new(.:format) list# category_new GET /c/:category/l/new(.:format) list# category_none_new GET /c/:category/none/l/new(.:format) list# parent_category_category_new GET /c/:parent_category/:category/l/new(.:format) list# read GET /read(.:format) list# category_read GET /c/:category/l/read(.:format) list# category_none_read GET /c/:category/none/l/read(.:format) list# parent_category_category_read GET /c/:parent_category/:category/l/read(.:format) list# posted GET /posted(.:format) list# category_posted GET /c/:category/l/posted(.:format) list# category_none_posted GET /c/:category/none/l/posted(.:format) list# parent_category_category_posted GET /c/:parent_category/:category/l/posted(.:format) list# bookmarks GET /bookmarks(.:format) list# category_bookmarks GET /c/:category/l/bookmarks(.:format) list# category_none_bookmarks GET /c/:category/none/l/bookmarks(.:format) list# parent_category_category_bookmarks GET /c/:parent_category/:category/l/bookmarks(.:format) list# B A C K E N D F O R F R O N T - Exploding number of specific “feature” APIs Generic APIs that over-fetch data
  • 7.
    1. With graphQLyou only get data which you exactly need, not more, not less 2. Multiple resources in single request 3. Validation and autocompletion GraphQL: No more Over- and Underfetching
  • 8.
    GraphQL Use Cases •GraphQL server with a connected database
 • GraphQL layer that integrates existing systems
  • 9.
    Hybrid approach withconnected database and integration of existing system
  • 10.
    GraphQL SDL -Schema Definition Language type Project { id: ID! //"!" denotes a required field name: String tagline: String contributors: [User] } type User { id: ID! name: String age: Int } A schema is a collection of types, interfaces, enums, and unions that make up your API’s data model Schema is strongly typed and self-documenting
  • 11.
    Core Concepts: TypeSystem • Scalar Types: Int, Float, String, Boolean, ID • Object Types: User, Project • Entry points: Query, Mutation, Subscription type Query { projects: [Project] project(id: ID!): Project user(id: ID!): User users: [User] } type Mutation { addUser(user: UserInput): User addProject(name: String!): Project }
  • 12.
    Schema Types • Scalartypes • Enumeration types
 • Interfaces • Union types • Input types • Fragments http://graphql.org/learn/schema/ scalar Date enum Episode { NEWHOPE EMPIRE JEDI } type Human implements Character { ….. } union SearchResult = Human | Droid | Starship
  • 13.
    Resolvers A function ona GraphQL server that's responsible for fetching the data for a single field, takes 4 arguments: Glue between schema types and actual data 1. parent : The result of the previous resolver call (more info). 2. args : The arguments of the resolver’s field. 3. context : A custom object each resolver can read from/write to 4. info : An AST representation of the query or mutation.
  • 14.
  • 15.
  • 16.
    Graphql Server Libraries •express-graphql: Bare minimum server for express • apollo-server: Works with multiply web frameworks but requires some of boilerplate • graphql-yoga: Simple setup, lots of tooling support e.g. realtime subscriptions, Graphql Playground. Uses apollo under hood.
  • 17.
    GraphQL-JS Hello-World var express= require('express'); var express_graphql = require('express-graphql'); var { buildSchema } = require('graphql'); // GraphQL schema var schema = buildSchema(` type Query { message: String } `); // Root resolver var root = { message: () => 'Hello World!' }; // Create an express server and a GraphQL endpoint var app = express(); app.use('/graphql', express_graphql({ schema: schema, rootValue: root, graphiql: true })); app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
  • 18.
    What is Apollo? Client-sidetooling ● Apollo Client ● Apollo iOS ● Apollo Android ● Dev tools ● apollo-codegen ● eslint-plugin-graphq Server-side tooling ● Apollo Server ● Graphql-tools
 ○ Schema creation ○ Mocking ○ Stitching ● Apollo Optics A set of projects designed to leverage GraphQL and work together to create a great workflow.
  • 19.
    Apollo Graphql Server constexpress = require('express'); const bodyParser = require('body-parser'); const { graphqlExpress, graphiqlExpress } = require('apollo-server-express'); const { makeExecutableSchema } = require('graphql-tools'); // Some fake data const books = [ … ] // The GraphQL schema in string form const typeDefs = ` type Query { books: [Book] } type Book { title: String, author: String } `; // The resolvers const resolvers = { Query: { books: () => books }, }; // Put together a schema const schema = makeExecutableSchema({ typeDefs, resolvers, }); // Initialize the app const app = express(); // The GraphQL endpoint app.use('/graphql', bodyParser.json(), graphqlExpress({ schema })); // GraphiQL, a visual editor for queries app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' })); // Start the server app.listen(3000, () => { console.log('Go to http://localhost:3000/graphiql to run queries!'); });
  • 20.
    A GraphQL APIin just a few lines of code link
  • 21.
    Bootstrap GraphQL Server $npm install -g graphql-cli $ graphql create your-cool-project --boilerplate typescript-advanced graphql-yoga + • GraphQL spec-compliant • File upload • GraphQL Subscriptions • TypeScript typings • GraphQL Playground • Extensible via Express middlewares • Apollo Tracing • Hosting (local or cloud) • control over your database schema • Extra stuff like authentication, email, etc
  • 22.
    GraphQL server architecture withPrisma Database GraphQL web server Prisma service Prisma is a GraphQL database proxy turning your database into a GraphQL API
  • 23.
  • 24.
    Main Module Authentification • express-jwtmiddleware + auth0 • pass encoded user in global context (which is available for all resolvers) • use @UseGuard to secure query or mutations (works like for routes)
  • 25.
  • 26.
  • 27.
  • 29.
    Apollo Client v2.0 •construct and send HTTP request (e.g. with fetch in Javascript) • receive and parse server response • store data locally (either simply in memory or persistent) npm install apollo-client apollo-angular apollo-cache-inmemory apollo-angular-link-http graphql graphql-tag --save
  • 30.
  • 31.
    Graphql JS IDEPlugin • Schema setup • completion • error highlighting • schema viewer, structure view • documentation Need to create graphql.config.json https://github.com/jimkyndemeyer/js-graphql-intellij-plugin
  • 32.
    Code Generation • Apollo-codegen apollo-codegenintrospect-schema / http://localhost:8080/graphql / —output ./src/app/graphql/schema.json apollo-codegen generate ./src/app/**/*.ts / —tag-name gql --schema ./src/app/graphql/ schema.json / —target typescript / —output ./src/app/graphql/operation-result- types.ts
  • 33.
  • 34.
  • 35.
  • 36.
    Conclusions • GraphQL APIshave a strongly typed schema • No more overfetching and underfetching • GraphQL enables rapid product development • Composing GraphQL APIs • Rich open-source ecosystem and an amazing community
  • 37.
    Useful Links • https://blog.graph.cool/graphql-server-basics-the-schema-ac5e2950214e •https://medium.com/@weblab_tech/graphql-everything-you-need-to-know-58756ff253d8 • https://blog.graph.cool/introducing-prisma-1ff423fd629e • https://blog.graph.cool/how-to-wrap-a-rest-api-with-graphql-8bf3fb17547d • https://blog.graph.cool/tutorial-how-to-build-a-graphql-server-with-graphql-yoga-6da86f346e68 • https://www.howtographql.com/graphql-js/1-getting-started/ • https://www.howtographql.com/advanced/0-clients/ • https://github.com/howtographql/angular-apollo • https://github.com/gsans/todo-apollo-v2