About.Me/mhunger
Michael Hunger
(Director of) Developer Relations Engineering, Neo4j
jexp.de/blog | @mesirii | github.com/jexp
I'm no expert in RESTful API design, development and deployment.
If in doubt ask the experts, like Stefan, Oliver, Jim, Ian, ...
I did a decent share of GraphQL though.
You ?
Have you heard of GraphQL?
Have you used GraphQL?
Did you attend the talks from Lars Röwekamp
or Manuel Mauky at OOP?
Some wise Words on Choosing an API Style
• Context matters
• API design styles are just tools
• Make an informed choice
• Choice will affect many aspects
(impl, dev-experience, lifecycle)
https://apihandyman.io/and-graphql-for-all-a-few-things-to-think-about-before-blindly-dumping-rest-for-graphql/
Remote API Techniques
•RPC (gRPC, CORBA)
•WS-* (SOAP)
•Publish / Subscribe
•Streaming Events (Kafka, Event Store)
•REST
•GraphQL
What is GraphQL ?
GraphQL is an API query language
The "Graph" is the application domain model
Specification & Reference Implementation
Expressive, extensible nested expressions
What is GraphQL not?
GraphQL is not a (graph) database query language
GraphQL is not a RESTful API
GraphQL is not a Silver Bullet
Why GraphQL?
We were frustrated with the differences between the data wewanted to use in our apps and the server queries theyrequired.
GraphQL was our opportunity to rethink mobile app data-fetching from the perspective of product designers anddevelopers.
It moved the focus of development to the client apps, wheredesigners and developers spend their time and attention.
GraphQL, a data query language. Post by Lee Byron
GraphQL - Origins?
• Facebook 2012• efficient queries for
mobile clients• minimize latency &
roundtrips• "get what you need"• pragmatic development
• Open Sourced 2015• Language Specificiation
• Reference Implementation
• Quickly Growing Community• esp. in Javascript (React)
• but also in backends
• Developer Tooling
• Working Group for Spec
Conference – App: Listing
{ onDay(day: Mi) {idtitlespeaker { name }track { name }slot { start, time }
}}
Conference - Result
{[{ id: "98a8ad", title: "Refactoring ..."speaker: [{ name: "Oliver Gierke" }]track: {name: "Modern Architecture"}slot: {start: 9:00, time: 60}
},...
]}
Conference – App: Details
{ talk(id:"98a8ad") {id, titlespeaker { name, pic }track { name }slot {
start, time, date}abstract, text, audience, level, req
}}
Conference - Result
{[{ id: "98a8ad", title: "Refactoring ..."speaker: [{ name: "Oliver Gierke",
pic: "http://..." }]track: {name: "Modern Architecture"}slot: {start: 9:00, time: 60, date: ".."}text: "", level: "Expert", req: "DDD..."
}]}
Reuse Retrieved Data
{ talk(id: "Mi 1.1") {id, titlespeaker { name, pic }track { name }slot { start, time, date}
abstract, text, audience, level, req
}}
Conference - Schema
type Talk {id: ID!title: String!abstract: Stringspeaker: [Person!]!slot: Slot!audience, level, ..
}
type Person {email: ID!name: String!talks: [Talk]
}type Slot {
day: Daystart: Time
}
Conference - Schema
type TalkMutations {rate(id:ID!, rating:Int, comment:String) : Talk
}
schema {mutations: TalkMutations
}
Conference - Mutation
mutation rate(id:2342,rating:5,comment:"Really useful") {
titlespeaker {
name}
}
Goals
• Developer productivity
• Focus on Front-End needs
• Enable Tool Building
• Fast Validation
• Clear Communication
What issues wants GraphQL to solve?
• one shape of resource vs. many different needs
• custom shape of data query
• type safe and valid
• latency & roundtrips
• updates as commands, http verbs not expressive enough
• language for communication between teams
• front-end & back-end can develop independently
• better developer tooling
Design Principles
•Hierarchical
•Product Centric (front-end)
• Introspective
•Strong Typing
•Client‐specified queries
Design Principles
• a language used to query application servers that have
capabilities defined in this specification
• does not mandate a particular programming language
or storage system
• map capabilities to a uniform language, type system, and philosophy
• unified interface friendly to product development
and a powerful platform for tool‐building
What is GraphQL Spec ?
• Formal language specification for schema & operations
• Developed by Working Group
• at Facebook
• collaborates with community
• Published (regularly) after updates
• Reference Implementation (JavaScript)
http://facebook.github.io/graphql/ http://graphql.org/learn/
What is in the GraphQL Spec ?
• Schema
• Types
• Query Language
• Mutations
• Subscriptons
• Extensibility
• Parameters
• Expected behavior
• Fragments
• Results & Errors
• No prescribed transport
• Mostly HTTP (GET or POST)
http://facebook.github.io/graphql/ http://graphql.org/learn/
Types
• Object Types
• Unions
• Interfaces
• Input Typ
• Enums
• Scalar Types
• Built-In:
Int, Float, String, Boolean, ID
• Nullability
• Arrays
https://github.com/sogko/graphql-schema-language-cheat-sheet
Query
http://facebook.github.io/graphql/ http://graphql.org/learn/
schema {query: QueryType
}
type QueryType {talksOnDay(day:Day) [Talk] @cached
}
Mutation
http://facebook.github.io/graphql/ http://graphql.org/learn/
schema {mutation: TalkUpdates
}
type TalkUpdates {rate(talk:Talk, rating:Int) Talk
}
Mutation
http://facebook.github.io/graphql/ http://graphql.org/learn/
input type RatingInput {talk: Talkrating: Int
}
type TalkUpdates {rate(rating:RatingInput) Talk
}
Subscriptions
type ConferenceSubscription {talkUpdated(track: String!): TalkUpdate
}
schema {subscription: ConferenceSubscription
}
https://www.apollographql.com/docs/graphql-subscriptions/subscriptions-to-schema.html
Subscriptions
subscription { talkUpdated(track: "Moderne Architektur") {
idtitlespeaker { name } slot { start, duration }
}}
https://www.apollographql.com/docs/graphql-subscriptions/subscriptions-to-schema.html
Subscriptions
•Mutations trigger Domain Events
•explicit or implicit
•Domain Event triggers Subscription update
•Websocket or HTTP transport / PubSub
•Supported in Clients
https://dev-blog.apollodata.com/tutorial-graphql-subscriptions-server-side-e51c32dc2951
Directive
http://facebook.github.io/graphql/ http://graphql.org/learn/
type Talk {speaker: [Person] @relation
(name:'PRESENTED',direction:OUT)duration: Int @deprecated
}
Others
• (named) Fragments
• Union, Interfaces, Enum
• Params with defaults
• Variables
• Aliases
• Multiple Operations
Executing GraphQL Requests
1. parse (syntax)
2. validate (semantics)
3. execute1. resolve fields2. combine results
4. return result or errors
new conceptField Resolver + Data Fetcher
possibly multiple operations per request
SQL
NOSQL
Static
REST
GraphQLServerGraphQL
Schema
Fiel
dR
eso
lver
+ D
ataF
etch
er
Parse
Validate
MergeResults
computed
GraphQL Transport
• Not prescribed
• Most often HTTP on /graphql
• POST or GET
• Hard to cache
• HTTP 200 with inline errors
• Monitoring / Tracing by middleware
GraphQL Auth
• In GraphQL server
• In Middleware before
• In Field resolver
•Use of directives @allowed(roles: [Admin])
SQL
NOSQL
Static
REST
computed
GraphQLServer
Mobile AppsSPA (React, Ang, Vue)API ConsumersEnd Users
Any Language / Platform
Middleware
Cache
Aggregator
Cache
Aggregator
Cache
Aggregator
GraphQL Development
1. Schema First – Agree on first iteration of schema
2. Register Schema
3. Implement Type Resolver
4. Fetch Data (static, db, api)
5. Implement Client App view with GraphQL client library
6. Iterate
GraphQL Uses
Larger Companies
• Consolidate sprawling APIs
• API domain language
• API Facades (Schema stitching)
• Wrap data sources & APIs
• Automatic API documentation
• API monitoring
• API evolution
Anyone (esp. Startups)
• Webapp development
• Mobile app development
• Quick Prototyping
• GraphQL as a service
Introspection
{ __type(name:"Talk") {namefields {namedescription
}}}
• in every backend
• queryable via graphql
• for validation
• type completion
• visualization
• fetching Schema SDLhttps://github.com/graphql-cli/graphql-cli
Documentation
# Conference Sessionstype Talk {
# id, e.g. Mi 3.2id: ID!title: String!abstract: String# multiple speakersspeaker: [Person!]!
}
• auto-generated from schema
• comments as docs
• browseable in client
• helpful for type completion
GraphQL DBaaS – Graph.Cool
• playground
• backed by database
• automatic mutation & query generation
• automatic field parameters
• auth
• serverless functions
• resolvers
• graph.cool / neo4j-graphql
GraphQL DB-API / DBaaS
• Prisma / GraphCool
• Join-Monster
• PostGraphQL / PostGraphile
• Neo4j-GraphQL
GraphQL Server Libraries (graphql-*)
• JavaScript
• Java
• Scala (Sangria)
• Ruby
• Python (Graphene)
• Go
• .Net
• PHP
• ...
GraphQL Community
• GraphQL Summit• 2016,2017,2018
• GraphQL-Europe• 2016, 2017
• GraphQL Slack• 4500 users
• Meetups• 65 groups
• 23000 members
RESTful API
• several resources, reachable via URI
• links between resources
• HTTP as protocol
• different representations / media-types, .e.g JSON
Philosophy & Guidelines
REST is software design on the scale of decades: everydetail is intended to promote software longevity andindependent evolution. Many of the constraints aredirectly opposed to short-term efficiency.
- Roy Fielding
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
Philosophy & Guidelines
I think most people just make the mistake that it shouldbe simple to design simple things. In reality, the effortrequired to design something is inversely proportional to the simplicity of the result. As architectural styles go, REST is very simple.
- Roy Fielding
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
New API Description Languages & Tools
• Not much tooling in first 5 years
• Web Service Description Language (WSDL)
• Web Application Description Language (WADL)
• Restful Service Description Language (RSDL)• HATEOAS – Hypermedia As The Engine Of Application State
• Swagger
• RESTful API Modeling Language (RAML)
GraphQL REST
free operation names for queries & mutations
HTTP Verbs
strong type safety none
operations are fields in schema Resources at URIs
model changes require schema + query changes
no API change through model change
addtive, deprecation, monitoring versioning, tagged resources
allows introspection communicates links to operations
depending on transport, minimally uses web infrastructure
strong tooling some tooling, depending on API tool
REST Benefits
• Well understood and known
• HTTP Protocol incl. Verbs
• Web Standards
• Web Infrastructure (Caching, Auth)
• Isolated Resources
• Dynamic links / data in REST API change client behavior
REST Issues
• Most RESTful API are just HTTP APIs
• Effort for complex queries (n+1, latency)
• Overfetching, Underfetching
• Versioning
GraphQL Benefits
• Type Safety
• Schema = Contract
• No overfetching, only resolve requested fields
• Single Request
• Combining Queries / Reusing existing Results
• Good set of libraries
• Explicit Specification + Reference Implementation
• Active Community / Drivers / Tools
GraphQL Issues
• Still New / Adoption
• Filtering
• Aggregation
• Auth
• Move aggregation to server
• Caching in Server & Client
• Larger Request Sizes
• Can't change hierarchy structure
Ressources
1. graphql.org
2. howtographql.com
3. github.com/chentsulin/awesome-graphql
4. graph.cool
5. github.com/graphql-java
6. Artikel MH JS 4/2017 (github.com/jexp/javaspektrum-graphql-demo)