SlideShare a Scribd company logo
1 of 64
Building a GraphQL API in
PHP@AndrewRota | PHPDetroit 2018
APIs are important
Native Mobile Apps
Web browsers
(XHR requests from JavaScript)
External API
API
Native Mobile Apps
Web browsers
External API
API
article
comment
comment
author
author
author
Native Mobile Apps
Web browsers
External API
API
article
comment
comment author
Native Mobile Apps
Web browsers
External API
APIgetBlog
Challenges with APIs Today
‣ Over-fetching data
‣ Under-fetching data, requiring multiple round-trips
‣ Time spent iterating on endpoints and expected data shape
GraphQL offers an alternative
architecture for developing
efficient, easy to understand APIs.
Andrew Rota
@AndrewRota
Associate Director, Software Engineering
What is
GraphQL?
“GraphQL is a query
language for APIs and a
runtime for fulfilling those
queries with your existing
data.”
{
conferences {
name
dates
}
}
"conferences": [
{
"name": "PHPDetroit",
"dates": "July 26-28, 2018"
}
]
{
conferences {
name
speakers {
name
twitter
}
}
}
{
"conferences": [
{
"name": "PHPDetroit Conference",
"speakers": [
{
"name": "Cal Evans",
"twitter": "https://twitter.com/CalEvans"
}
]
}
]
}
Topics
‣ Introduction
‣ GraphQL Concepts
‣ Client-Side GraphQL
‣ Server-side GraphQL with PHP
‣ Beyond the Basics
‣ GraphQL Tooling
GraphQL
‣ Developed internally at Facebook in 2012
‣ Open sourced in 2015
‣ Spec: facebook.github.io/graphql/draft
GraphQL Implementations
‣ GraphQL is technology agnostic on both client and server
‣ Client implementations:
‣ Server implementations:
GraphQL Advantages
‣ Client requests exactly the shape of the data it needs
‣ Multiple resources can be queried in a single request
‣ API is defined with a strongly-typed schema
‣ Enables strong tooling for developers
GraphQL in a web stack
QueryClient
(e.g., browser, mobile
app)
/graphql on
PHP Server
response
Database
GraphQL in a web stack
QueryClient
(e.g., browser, mobile
app)
/graphql on
PHP Server
response
Cache
Service
Database
GraphQL in a web stack
QueryClient
(e.g., browser, mobile
app)
/graphql
server
response
Cache
REST Service
Database
PHP
GraphQL Concepts
Queries + Fields
‣ In GraphQL you make
queries for fields on objects
‣ The response will have the
same shape as the query
query {
conferences {
name
dates
}
}
quer
y
field
Fields
‣ Fields might be scalar values,
or they might be other
Objects.
‣ Fields can refer to Objects,
and you can make a sub-
selection for fields of these
Objects.
‣ This lets you avoid making
multiple requests for related
query {
conferences {
name
speakers {
name
}
}
}
sub-selection
Arguments
‣ You can pass named
arguments to each field
and nested object.
{
conference(name: "PHPDetroit") {
speakers {
name
}
}
}
argument
Variables
‣ Dynamic values can be
passed into queries via
variables
query SearchConfs($name: String){
conferences(nameFilter:$name) {
name
}
}
{"name": "Detroit"}
Types + Schemas
‣ Every GraphQL service
defines the a set of types
that describe what data can
be requested
Types + Schemas
‣ GraphQL servers can be
written in any language, so
we describe types with a
language-agnostic
“GraphQL schema
language”
type Conference {
name: String!
url: String!
description: String
location: String
dates: String!
# List of speakers at this conference
speakers: [Speaker]
}
Types + Schemas
‣ GraphQL servers can be
written in any language, so
we describe types with a
language-agnostic
“GraphQL schema
language”
‣ Types include: object,
scalar, list, enumeration,
union, interface, and non-
nullable.
type Conference {
name: String!
url: String!
description: String
location: String
dates: String!
# List of speakers at this conference
speakers: [Speaker]
}
non-nullable
scalar type
list of
object
types
Query + Mutation Types
‣ There are two special types
in every GraphQL schema:
Query and Mutation
‣ Root fields you define on
Query and Mutation are the
entry points of requests
type Query {
# Returns conferences
conferences: [Conference]
# Returns speakers
speakers: [Speaker]
}
root
fields
root type
Queries
‣ Queries ask for for data;
analogous to GET requests.
‣ GraphQL clients (e.g.,
browsers, mobile apps),
make queries against a
single GraphQL endpoint
‣ Operation name and type
can be optional
query ConferenceNamesAndDates{
conferences {
name
dates
}
}
operation nameoperation type
fields
Mutations
‣ Mutations are for modifying
data; analogous to
POST/PUT/DELETE
requests.
‣ They start with the
mutation root type, and
will often leverage
arguments, but are
otherwise the same as
queries
mutation {
addSpeaker(
name: "Andrew Rota",
twitter: "https://twitter.com/andrewrota")
{
id
}
}
GraphQL on the Client
Client-side GraphQL is about writing queries to request data
from a GraphQL server with a defined schema.
Queries from JavaScript
‣ Queries are made via HTTP
requests to a single
endpoint
‣ There are several libraries
available to manage
GraphQL on the client
query ConferenceNamesAndDates{
conferences {
name
dates
}
}
Queries from JavaScript
‣ lokka-http-transport is a
simple JavaScript library for
sending GraphQL queries in
JavaScript, just like
standard fetch or ajax
requests
const t = new HttpTransport('/graphql');
t.send(`query ConferenceNamesAndDates{
conferences {
name
dates
}
}`).then(response => {
console.log(response);
});
Advanced GraphQL Client Libraries
There are also more advanced GraphQL
clients with features such as...
‣ Declarative data fetching patterns
‣ Client-side caching
‣ Abstractions for managing local +
remote state
‣ Integration with react.js or other
frontend libraries
GraphQL on the Server
webonyx/graphql-php
Provides:
‣ Type primitives for your Type system
‣ Query parsing, validation, and
execution against a Type system
‣ Type introspection
‣ Tools for deferred field resolution
Feature-complete implementation of the
GraphQL spec in PHP, inspired by
Facebook’s original node-js reference
library.
webonyx/graphql-php
Used by:
‣ Folkloreatelier/laravel-graphql
‣ overblog/GraphQLBundle (symfony)
‣ ivome/graphql-relay-php
‣ wp-graphql/wp-graphql
‣ tim-field/graphql-wp
Feature-complete implementation of the
GraphQL spec in PHP, inspired by
Facebook’s original node-js reference
library.
Client-side GraphQL is about writing queries to request data
from a GraphQL server with a defined schema.
Server-side GraphQL is about implementing that schema to
return data.
1. Parse the query into an AST
2. Validate the query against the schema
3. Traverse the query, breadth first, and execute a resolver
function for each field
The schema defines what queries can be made, what types of
data can be requested, and the relationships between those
types
The resolver functions define how to get the data for each
field.
definition
implementation
1. Define your object type
2. Add it to a new field
3. Write the field resolver function
Begin with some boilerplate code to handle queries.
Handle queries
‣ Queries are made via HTTP
requests
‣ Schema instance contains
your type hierarchy, and
starts with the special root
types, Query and Mutation.
‣ GraphQL::executeQuery
executes the query and
returns the result (or failure)
$schema = new Schema([
'query' => Types::query()
]);
$result = GraphQL::executeQuery(
$schema,
$requestData['query'],
null,
$appContext,
(array)$requestData['variables']
);
$output = $result->toArray($debug);
Then start with the special root type, Query.
Start with the Query type
‣ ObjectType is a collection
of fields
‣ Query has root fields, the
entry points for queries.
‣ Each field must have a
name and type. It can also
have a resolve function,
args, description, and
other properties.
use GraphQLTypeDefinitionObjectType;
use GraphQLTypeDefinitionType;
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'type' => Type::string(),
'args' => [
'message' => Type::nonNull(Type::string()),
],
'resolve' => function ($root, $args) {
return 'hello ' . $args['message'];
}
],
]
]);
Add a root field
‣ Type can be an Array of
some type; use
Types::listOf()
‣ Resolve function can be
implemented however you’d
like to get the data: query
SQL or NoSQL databases,
access in-memory storage,
or query another API
endpoint.
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'conferences' => [
'type' => Types::listOf(Types::conference()),
'description' => 'Returns list of PHP
conferences',
'resolve' => function() {
return DataSource::getConferences();
}
]
]
]);
Implement its Type
‣ Type can be an Array of
some type; use
Types::listOf()
‣ 3 ways to define resolvers:
○ Default field resolver (built-
in)
○ Default Field Resolver per
Type (resolveField option in
type config)
○ Field resolver (resolve option
$config = [
'name' => 'Conference',
'fields' => [
'name' => Type::nonNull(Types::string()),
'url' => Type::nonNull(Types::string()),
'location' => Types::string(),
]
];
precedence
Let’s add another field
'fields' => [
'name' => Type::nonNull(Types::string()),
'url' => Type::nonNull(Types::string()),
'location' => Types::string(),
'speakers' => [
'type' => Types::listOf(Types::speaker()),
'description' => 'List of speakers at this
conference',
'resolve' => function($root) {
return
DataSource::getSpeakersAtConference($root->id);
}
]
],
...and take a closer look at the resolve function
[
'resolveField' => function($root, $args, $context, ResolveInfo $info) {
return DataSource::getSpeakersAtConference($root->id);
}
]
root / parent
result
arguments app context
query AST and
other meta info
Building a GraphQL server is primarily about structuring schema
types, and then implementing their field resolvers
Beyond the Basics
n+1 problem
‣ Data-fetching problem that
occurs when you need to
fetch related items in a one-
to-many relationship
{
conferences {
name
speakers{
name
}
}
}
Solution: deferred resolvers
‣ We can use deferreds to delay field
resolution until we can make a
single batch request for the data
‣ Once all non-deferred fields are
resolved, graphql-php will call the
wrapped closures
‣ If you have an environment that
supports async operations (e.g.,
HHVM, ReactPHP, PHP threads),
some fields can also resolve async.
'resolve' => function($root) {
SpeakerCollection::add($root->id);
return new Deferred(function() use ($root) {
return SpeakerCollection::get($root->id);
});
}
Persisted Queries
queryClient Server
query {
conferences {
name
dates
}
}
idClient Server{ id: 001 }
‣ In production, queries can
be extracted at build-time
as “persisted queries”
‣ Clients send the server the
reference to the query
‣ Reduce data sent to server
‣ Restrict queries that can be
run to a pre-built whitelist
With persisted queries:
GraphQL Tooling
Introspection
‣ A key feature of GraphQL is
its introspection system
‣ You can ask any GraphQL
schema about what queries
it supports
‣ This unlocks opportunities
for powerful tooling
{
"data": {
"__schema": {
"queryType": {
"name": "Query"
},
"types": [
{
"kind": "OBJECT",
"name": "Query",
"description": null,
"fields": [
{
"name": "conferences",
"description": "Returns a list of PHP conferences",
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Conference",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
]
}
]
}
}
}
GraphiQL - in browser IDE for exploring GraphQL
Voyager - Any GraphQL API as an interactive graph
PHPStorm JS GraphQL Plugin - IDE Integration
GraphQL makes it easier to make
more efficient queries between your
client and your server.
GraphQL provides new ways to
think about your APIs and the
structure of your application’s data.
Give it a try!
Thanks!
Andrew Rota
@AndrewRota
Resources
‣ graphql.org
‣ github.com/webonyx/graphql-php
‣ github.com/chentsulin/awesome-
graphql
‣ howtographql.com

More Related Content

What's hot

An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQLvaluebound
 
Better APIs with GraphQL
Better APIs with GraphQL Better APIs with GraphQL
Better APIs with GraphQL Josh Price
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQLMuhilvarnan V
 
Magento2.3 - GraphQL introduction
Magento2.3  - GraphQL introductionMagento2.3  - GraphQL introduction
Magento2.3 - GraphQL introductionVishakha Borkar
 
Flutter vs React Native | Edureka
Flutter vs React Native | EdurekaFlutter vs React Native | Edureka
Flutter vs React Native | EdurekaEdureka!
 
정규표현식(Regular expressions)
정규표현식(Regular expressions)정규표현식(Regular expressions)
정규표현식(Regular expressions)Juhee Kim
 
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Hafiz Ismail
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampTheo Jungeblut
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaMarcinStachniuk
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLAppier
 

What's hot (20)

An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Better APIs with GraphQL
Better APIs with GraphQL Better APIs with GraphQL
Better APIs with GraphQL
 
React & GraphQL
React & GraphQLReact & GraphQL
React & GraphQL
 
GraphQL Fundamentals
GraphQL FundamentalsGraphQL Fundamentals
GraphQL Fundamentals
 
React Native
React NativeReact Native
React Native
 
React Context API
React Context APIReact Context API
React Context API
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQL
 
Magento2.3 - GraphQL introduction
Magento2.3  - GraphQL introductionMagento2.3  - GraphQL introduction
Magento2.3 - GraphQL introduction
 
Flutter vs React Native | Edureka
Flutter vs React Native | EdurekaFlutter vs React Native | Edureka
Flutter vs React Native | Edureka
 
정규표현식(Regular expressions)
정규표현식(Regular expressions)정규표현식(Regular expressions)
정규표현식(Regular expressions)
 
Intro to GraphQL
 Intro to GraphQL Intro to GraphQL
Intro to GraphQL
 
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
 
Angular
AngularAngular
Angular
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 

Similar to Building a GraphQL API in PHP

Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHPAndrew Rota
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB
 
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScriptMongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScriptMongoDB
 
How to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that wayHow to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that wayQAware GmbH
 
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessYour API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessQAware GmbH
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionVMware Tanzu
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessConnected Data World
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and serverPavel Chertorogov
 
Modern APIs with GraphQL
Modern APIs with GraphQLModern APIs with GraphQL
Modern APIs with GraphQLTaikai
 
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)Shift Conference
 
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...Databricks
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma CloudNikolas Burk
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchNikolas Burk
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLiteJEAN-GUILLAUME DUJARDIN
 
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)Rob Crowley
 
All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...
All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...
All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...GreeceJS
 

Similar to Building a GraphQL API in PHP (20)

Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHP
 
Graphql usage
Graphql usageGraphql usage
Graphql usage
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
 
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScriptMongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
 
GraphQL + relay
GraphQL + relayGraphQL + relay
GraphQL + relay
 
How to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that wayHow to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that way
 
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessYour API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database access
 
GraphQL
GraphQLGraphQL
GraphQL
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and server
 
Hands On - GraphQL
Hands On - GraphQLHands On - GraphQL
Hands On - GraphQL
 
Modern APIs with GraphQL
Modern APIs with GraphQLModern APIs with GraphQL
Modern APIs with GraphQL
 
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
 
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma Cloud
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
 
PHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLitePHP, the GraphQL ecosystem and GraphQLite
PHP, the GraphQL ecosystem and GraphQLite
 
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
 
All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...
All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...
All About GRAND Stack: GraphQL, React, Apollo, and Neo4j (Mark Needham) - Gre...
 

More from Andrew Rota

Integrating React.js Into a PHP Application: Dutch PHP 2019
Integrating React.js Into a PHP Application: Dutch PHP 2019Integrating React.js Into a PHP Application: Dutch PHP 2019
Integrating React.js Into a PHP Application: Dutch PHP 2019Andrew Rota
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performanceAndrew Rota
 
Component Based UI Architectures for the Web
Component Based UI Architectures for the WebComponent Based UI Architectures for the Web
Component Based UI Architectures for the WebAndrew Rota
 
Client-Side Performance Monitoring (MobileTea, Rome)
Client-Side Performance Monitoring (MobileTea, Rome)Client-Side Performance Monitoring (MobileTea, Rome)
Client-Side Performance Monitoring (MobileTea, Rome)Andrew Rota
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationAndrew Rota
 
Effectively Monitoring Client-Side Performance
Effectively Monitoring Client-Side PerformanceEffectively Monitoring Client-Side Performance
Effectively Monitoring Client-Side PerformanceAndrew Rota
 
UI Rendering at Wayfair
UI Rendering at WayfairUI Rendering at Wayfair
UI Rendering at WayfairAndrew Rota
 
Better PHP-Frontend Integration with Tungsten.js
Better PHP-Frontend Integration with Tungsten.jsBetter PHP-Frontend Integration with Tungsten.js
Better PHP-Frontend Integration with Tungsten.jsAndrew Rota
 
Tungsten.js: Building a Modular Framework
Tungsten.js: Building a Modular FrameworkTungsten.js: Building a Modular Framework
Tungsten.js: Building a Modular FrameworkAndrew Rota
 
Why Static Type Checking is Better
Why Static Type Checking is BetterWhy Static Type Checking is Better
Why Static Type Checking is BetterAndrew Rota
 
An Exploration of Frameworks – and Why We Built Our Own
An Exploration of Frameworks – and Why We Built Our OwnAn Exploration of Frameworks – and Why We Built Our Own
An Exploration of Frameworks – and Why We Built Our OwnAndrew Rota
 
The Complementarity of React and Web Components
The Complementarity of React and Web ComponentsThe Complementarity of React and Web Components
The Complementarity of React and Web ComponentsAndrew Rota
 
Web Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationWeb Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationAndrew Rota
 
Web Components and Modular CSS
Web Components and Modular CSSWeb Components and Modular CSS
Web Components and Modular CSSAndrew Rota
 

More from Andrew Rota (15)

Integrating React.js Into a PHP Application: Dutch PHP 2019
Integrating React.js Into a PHP Application: Dutch PHP 2019Integrating React.js Into a PHP Application: Dutch PHP 2019
Integrating React.js Into a PHP Application: Dutch PHP 2019
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performance
 
Component Based UI Architectures for the Web
Component Based UI Architectures for the WebComponent Based UI Architectures for the Web
Component Based UI Architectures for the Web
 
Client-Side Performance Monitoring (MobileTea, Rome)
Client-Side Performance Monitoring (MobileTea, Rome)Client-Side Performance Monitoring (MobileTea, Rome)
Client-Side Performance Monitoring (MobileTea, Rome)
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Effectively Monitoring Client-Side Performance
Effectively Monitoring Client-Side PerformanceEffectively Monitoring Client-Side Performance
Effectively Monitoring Client-Side Performance
 
UI Rendering at Wayfair
UI Rendering at WayfairUI Rendering at Wayfair
UI Rendering at Wayfair
 
Better PHP-Frontend Integration with Tungsten.js
Better PHP-Frontend Integration with Tungsten.jsBetter PHP-Frontend Integration with Tungsten.js
Better PHP-Frontend Integration with Tungsten.js
 
Tungsten.js: Building a Modular Framework
Tungsten.js: Building a Modular FrameworkTungsten.js: Building a Modular Framework
Tungsten.js: Building a Modular Framework
 
Why Static Type Checking is Better
Why Static Type Checking is BetterWhy Static Type Checking is Better
Why Static Type Checking is Better
 
An Exploration of Frameworks – and Why We Built Our Own
An Exploration of Frameworks – and Why We Built Our OwnAn Exploration of Frameworks – and Why We Built Our Own
An Exploration of Frameworks – and Why We Built Our Own
 
The Complementarity of React and Web Components
The Complementarity of React and Web ComponentsThe Complementarity of React and Web Components
The Complementarity of React and Web Components
 
Web Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationWeb Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing Combination
 
Bem methodology
Bem methodologyBem methodology
Bem methodology
 
Web Components and Modular CSS
Web Components and Modular CSSWeb Components and Modular CSS
Web Components and Modular CSS
 

Recently uploaded

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Building a GraphQL API in PHP

  • 1. Building a GraphQL API in PHP@AndrewRota | PHPDetroit 2018
  • 2. APIs are important Native Mobile Apps Web browsers (XHR requests from JavaScript) External API API
  • 3. Native Mobile Apps Web browsers External API API article comment comment author author author
  • 4. Native Mobile Apps Web browsers External API API article comment comment author
  • 5. Native Mobile Apps Web browsers External API APIgetBlog
  • 6. Challenges with APIs Today ‣ Over-fetching data ‣ Under-fetching data, requiring multiple round-trips ‣ Time spent iterating on endpoints and expected data shape
  • 7. GraphQL offers an alternative architecture for developing efficient, easy to understand APIs.
  • 9. What is GraphQL? “GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.”
  • 10. { conferences { name dates } } "conferences": [ { "name": "PHPDetroit", "dates": "July 26-28, 2018" } ]
  • 11. { conferences { name speakers { name twitter } } } { "conferences": [ { "name": "PHPDetroit Conference", "speakers": [ { "name": "Cal Evans", "twitter": "https://twitter.com/CalEvans" } ] } ] }
  • 12. Topics ‣ Introduction ‣ GraphQL Concepts ‣ Client-Side GraphQL ‣ Server-side GraphQL with PHP ‣ Beyond the Basics ‣ GraphQL Tooling
  • 13. GraphQL ‣ Developed internally at Facebook in 2012 ‣ Open sourced in 2015 ‣ Spec: facebook.github.io/graphql/draft
  • 14. GraphQL Implementations ‣ GraphQL is technology agnostic on both client and server ‣ Client implementations: ‣ Server implementations:
  • 15. GraphQL Advantages ‣ Client requests exactly the shape of the data it needs ‣ Multiple resources can be queried in a single request ‣ API is defined with a strongly-typed schema ‣ Enables strong tooling for developers
  • 16. GraphQL in a web stack QueryClient (e.g., browser, mobile app) /graphql on PHP Server response Database
  • 17. GraphQL in a web stack QueryClient (e.g., browser, mobile app) /graphql on PHP Server response Cache Service Database
  • 18. GraphQL in a web stack QueryClient (e.g., browser, mobile app) /graphql server response Cache REST Service Database PHP
  • 20. Queries + Fields ‣ In GraphQL you make queries for fields on objects ‣ The response will have the same shape as the query query { conferences { name dates } } quer y field
  • 21. Fields ‣ Fields might be scalar values, or they might be other Objects. ‣ Fields can refer to Objects, and you can make a sub- selection for fields of these Objects. ‣ This lets you avoid making multiple requests for related query { conferences { name speakers { name } } } sub-selection
  • 22. Arguments ‣ You can pass named arguments to each field and nested object. { conference(name: "PHPDetroit") { speakers { name } } } argument
  • 23. Variables ‣ Dynamic values can be passed into queries via variables query SearchConfs($name: String){ conferences(nameFilter:$name) { name } } {"name": "Detroit"}
  • 24. Types + Schemas ‣ Every GraphQL service defines the a set of types that describe what data can be requested
  • 25. Types + Schemas ‣ GraphQL servers can be written in any language, so we describe types with a language-agnostic “GraphQL schema language” type Conference { name: String! url: String! description: String location: String dates: String! # List of speakers at this conference speakers: [Speaker] }
  • 26. Types + Schemas ‣ GraphQL servers can be written in any language, so we describe types with a language-agnostic “GraphQL schema language” ‣ Types include: object, scalar, list, enumeration, union, interface, and non- nullable. type Conference { name: String! url: String! description: String location: String dates: String! # List of speakers at this conference speakers: [Speaker] } non-nullable scalar type list of object types
  • 27. Query + Mutation Types ‣ There are two special types in every GraphQL schema: Query and Mutation ‣ Root fields you define on Query and Mutation are the entry points of requests type Query { # Returns conferences conferences: [Conference] # Returns speakers speakers: [Speaker] } root fields root type
  • 28. Queries ‣ Queries ask for for data; analogous to GET requests. ‣ GraphQL clients (e.g., browsers, mobile apps), make queries against a single GraphQL endpoint ‣ Operation name and type can be optional query ConferenceNamesAndDates{ conferences { name dates } } operation nameoperation type fields
  • 29. Mutations ‣ Mutations are for modifying data; analogous to POST/PUT/DELETE requests. ‣ They start with the mutation root type, and will often leverage arguments, but are otherwise the same as queries mutation { addSpeaker( name: "Andrew Rota", twitter: "https://twitter.com/andrewrota") { id } }
  • 30. GraphQL on the Client
  • 31. Client-side GraphQL is about writing queries to request data from a GraphQL server with a defined schema.
  • 32. Queries from JavaScript ‣ Queries are made via HTTP requests to a single endpoint ‣ There are several libraries available to manage GraphQL on the client query ConferenceNamesAndDates{ conferences { name dates } }
  • 33. Queries from JavaScript ‣ lokka-http-transport is a simple JavaScript library for sending GraphQL queries in JavaScript, just like standard fetch or ajax requests const t = new HttpTransport('/graphql'); t.send(`query ConferenceNamesAndDates{ conferences { name dates } }`).then(response => { console.log(response); });
  • 34. Advanced GraphQL Client Libraries There are also more advanced GraphQL clients with features such as... ‣ Declarative data fetching patterns ‣ Client-side caching ‣ Abstractions for managing local + remote state ‣ Integration with react.js or other frontend libraries
  • 35. GraphQL on the Server
  • 36. webonyx/graphql-php Provides: ‣ Type primitives for your Type system ‣ Query parsing, validation, and execution against a Type system ‣ Type introspection ‣ Tools for deferred field resolution Feature-complete implementation of the GraphQL spec in PHP, inspired by Facebook’s original node-js reference library.
  • 37. webonyx/graphql-php Used by: ‣ Folkloreatelier/laravel-graphql ‣ overblog/GraphQLBundle (symfony) ‣ ivome/graphql-relay-php ‣ wp-graphql/wp-graphql ‣ tim-field/graphql-wp Feature-complete implementation of the GraphQL spec in PHP, inspired by Facebook’s original node-js reference library.
  • 38. Client-side GraphQL is about writing queries to request data from a GraphQL server with a defined schema. Server-side GraphQL is about implementing that schema to return data.
  • 39. 1. Parse the query into an AST 2. Validate the query against the schema 3. Traverse the query, breadth first, and execute a resolver function for each field
  • 40. The schema defines what queries can be made, what types of data can be requested, and the relationships between those types The resolver functions define how to get the data for each field. definition implementation
  • 41. 1. Define your object type 2. Add it to a new field 3. Write the field resolver function
  • 42. Begin with some boilerplate code to handle queries.
  • 43. Handle queries ‣ Queries are made via HTTP requests ‣ Schema instance contains your type hierarchy, and starts with the special root types, Query and Mutation. ‣ GraphQL::executeQuery executes the query and returns the result (or failure) $schema = new Schema([ 'query' => Types::query() ]); $result = GraphQL::executeQuery( $schema, $requestData['query'], null, $appContext, (array)$requestData['variables'] ); $output = $result->toArray($debug);
  • 44. Then start with the special root type, Query.
  • 45. Start with the Query type ‣ ObjectType is a collection of fields ‣ Query has root fields, the entry points for queries. ‣ Each field must have a name and type. It can also have a resolve function, args, description, and other properties. use GraphQLTypeDefinitionObjectType; use GraphQLTypeDefinitionType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'hello' => [ 'type' => Type::string(), 'args' => [ 'message' => Type::nonNull(Type::string()), ], 'resolve' => function ($root, $args) { return 'hello ' . $args['message']; } ], ] ]);
  • 46. Add a root field ‣ Type can be an Array of some type; use Types::listOf() ‣ Resolve function can be implemented however you’d like to get the data: query SQL or NoSQL databases, access in-memory storage, or query another API endpoint. $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'conferences' => [ 'type' => Types::listOf(Types::conference()), 'description' => 'Returns list of PHP conferences', 'resolve' => function() { return DataSource::getConferences(); } ] ] ]);
  • 47. Implement its Type ‣ Type can be an Array of some type; use Types::listOf() ‣ 3 ways to define resolvers: ○ Default field resolver (built- in) ○ Default Field Resolver per Type (resolveField option in type config) ○ Field resolver (resolve option $config = [ 'name' => 'Conference', 'fields' => [ 'name' => Type::nonNull(Types::string()), 'url' => Type::nonNull(Types::string()), 'location' => Types::string(), ] ]; precedence
  • 48. Let’s add another field 'fields' => [ 'name' => Type::nonNull(Types::string()), 'url' => Type::nonNull(Types::string()), 'location' => Types::string(), 'speakers' => [ 'type' => Types::listOf(Types::speaker()), 'description' => 'List of speakers at this conference', 'resolve' => function($root) { return DataSource::getSpeakersAtConference($root->id); } ] ],
  • 49. ...and take a closer look at the resolve function [ 'resolveField' => function($root, $args, $context, ResolveInfo $info) { return DataSource::getSpeakersAtConference($root->id); } ] root / parent result arguments app context query AST and other meta info
  • 50. Building a GraphQL server is primarily about structuring schema types, and then implementing their field resolvers
  • 52. n+1 problem ‣ Data-fetching problem that occurs when you need to fetch related items in a one- to-many relationship { conferences { name speakers{ name } } }
  • 53. Solution: deferred resolvers ‣ We can use deferreds to delay field resolution until we can make a single batch request for the data ‣ Once all non-deferred fields are resolved, graphql-php will call the wrapped closures ‣ If you have an environment that supports async operations (e.g., HHVM, ReactPHP, PHP threads), some fields can also resolve async. 'resolve' => function($root) { SpeakerCollection::add($root->id); return new Deferred(function() use ($root) { return SpeakerCollection::get($root->id); }); }
  • 54. Persisted Queries queryClient Server query { conferences { name dates } } idClient Server{ id: 001 } ‣ In production, queries can be extracted at build-time as “persisted queries” ‣ Clients send the server the reference to the query ‣ Reduce data sent to server ‣ Restrict queries that can be run to a pre-built whitelist With persisted queries:
  • 56. Introspection ‣ A key feature of GraphQL is its introspection system ‣ You can ask any GraphQL schema about what queries it supports ‣ This unlocks opportunities for powerful tooling { "data": { "__schema": { "queryType": { "name": "Query" }, "types": [ { "kind": "OBJECT", "name": "Query", "description": null, "fields": [ { "name": "conferences", "description": "Returns a list of PHP conferences", "args": [], "type": { "kind": "LIST", "name": null, "ofType": { "kind": "OBJECT", "name": "Conference", "ofType": null } }, "isDeprecated": false, "deprecationReason": null } ] } ] } } }
  • 57. GraphiQL - in browser IDE for exploring GraphQL
  • 58. Voyager - Any GraphQL API as an interactive graph
  • 59. PHPStorm JS GraphQL Plugin - IDE Integration
  • 60. GraphQL makes it easier to make more efficient queries between your client and your server.
  • 61. GraphQL provides new ways to think about your APIs and the structure of your application’s data.
  • 62. Give it a try!
  • 64. Andrew Rota @AndrewRota Resources ‣ graphql.org ‣ github.com/webonyx/graphql-php ‣ github.com/chentsulin/awesome- graphql ‣ howtographql.com