SlideShare a Scribd company logo
Performant APIs with GraphQL and PHP
@AndrewRota | Dutch PHP Conference 2019
APIs are important
Native Mobile Apps
Web browsers
(http 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 Traditional APIs
‣ 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": "Dutch PHP 2019",
"dates": "June 6-8, 2019"
}
]
{
conferences {
name
speakers {
name
twitter
}
}
}
{
"conferences": [
{
"name": "Dutch PHP 2019",
"speakers": [
{
"name": "Andrew Rota",
"twitter": "https://twitter.com/andrewrota"
}
]
}
]
}
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
}
}
query
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
resources
query {
conferences {
name
speakers {
name
}
}
}
sub-selection
Arguments
‣ You can pass named
arguments to each field
and nested object.
{
conference(name: "LonghornPHP") {
speakers {
name
}
}
}
argument
Variables
‣ Dynamic values can be
passed into queries via
variables
query SearchConfs($name: String){
conferences(nameFilter:$name) {
name
}
}
{"name": "LonghornPHP"}
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
}
}
Lokka
a simple graphql client library
‣ Lokka 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);
});
Apollo
complete data management solution
‣ Declarative API for queries and
mutations
‣ Normalized client-side caching
‣ Combine local and remote data
‣ Pagination, error handling,
refetching, and optimistic UI
‣ Client libraries for popular frontend
frameworks (React.js, Angular, Vue),
as well as native Android and iOS
applications
<Query client={client} query={CONFERENCES_QUERY}>
{({ loading, error, data }) => {
if (loading) return 'Loading...';
if (error) return `Error!`;
return (
<ul>
{data.conferences.map(conference => (
<li>{conference.name}</li>
))}
</ul>
);
}}
</Query>
GraphQL on the Server
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.
Let’s build a GraphQL server in PHP!
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.
Create a /graphql endpoint to handle requests, and execute queries
Handle queries
‣ Queries are made via HTTP
requests to a single endpoint
‣ GraphQL::executeQuery
parses, validates, and
executes the query
$schema = new Schema([
'query' => Types::query()
]);
$result = GraphQL::executeQuery(
$schema,
$requestData['query'],
null,
$appContext,
(array)$requestData['variables']
);
$output = $result->toArray();
Then start with the special root type, Query.
Root fields
‣ This root type (Query) has a
list of root fields, which are
the entry points to the API
‣ Each field has a type, and a
resolve method for getting
the data
use GraphQLTypeDefinitionObjectType;
use GraphQLTypeDefinitionType;
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'message' => [
'type' => Type::string(),
'resolve' => function () {
return 'hello world';
}
],
]
]);
Fields can return objects
‣ A field can also return a
custom ObjectType, which is
a type with its own collection
of fields.
‣ It can also return lists of other
types
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'conferences' => [
'type' => Types::listOf(Types::conference()),
'description' => 'Returns conferences',
'resolve' => function() {
return DataSource::getConferences();
}
],
'message' => [
'type' => Type::string(),
'resolve' => function () {
return 'hello world';
}
],
]
]);
Resolvers
‣ Resolve functions tell the server
how to get the data for the field
‣ Resolve function can be
implemented however you’d like to
get the data: SQL queries, cache, or
another API
‣ For scalars, the return value will be
the value of the field
‣ For object types, the return value
will be passed on to nested fields
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'conferences' => [
'type' => Types::listOf(Types::conference()),
'description' => 'Returns conferences',
'resolve' => function() {
return DataSource::getConferences();
}
],
'message' => [
'type' => Type::string(),
'resolve' => function () {
return 'hello world';
}
],
]
]);
...let’s take a closer look at a resolve function
function($root, $args, $context, ResolveInfo $info) {
return DataSource::getData($root->id);
}
root / parent
result
arguments app context
query AST and
other meta info
Creating a custom ObjectType
1. Define your object type
2. Add it to a new field
3. Write the field resolver function
Custom object type
‣ Just like the root query type,
a custom type is a collection
of fields, each with their own
types
$config = [
'name' => 'Conference',
'fields' => [
'name' => Type::nonNull(Types::string()),
'url' => Type::nonNull(Types::string()),
'location' => Types::string(),
]
];
Custom object type
‣ Just like the root query type,
a custom type is a collection
of fields, each with their own
types
‣ Fields on a type can also
have custom ObjectTypes
$config = [
'name' => 'Conference',
'fields' => [
'name' => Type::nonNull(Types::string()),
'url' => Type::nonNull(Types::string()),
'location' => Types::string(),
'speakers' => [
'type' => Types::listOf(Types::speaker()),
'resolve' => function($root) {
return DataSource::getSpeakersAtConf($root->id);
}
]
]
];
And now we have a GraphQL server!
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
Graphql Playground - like GraphiQL, but more features
Voyager - Any GraphQL API as an interactive graph
PHPStorm JS GraphQL Plugin - IDE Integration
Types can be used in client-side code
‣ If you’re using a client-side language that supports types, you can
generate types for graphql queries automatically from the GraphQL
schema using tools such as Apollo Codegen
‣ Examples: TypeScript, FlowType, or Swift (iOS)
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
‣ graphql-php provides Deferred
objects 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);
});
}
Limiting Query Complexity and Depth
‣ graphql-php provides a method to calculate and limit the complexity
of any query, based on the sum of complexity scores set per field
‣ You can also limit the nested fields requested in queries
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:
Subscriptions
Client Server
Subscribe to an event
‣ GraphQL subscriptions push
data to the client when
events happen, usually over
a long-lived WebSocket
connection.
‣ graphql-php does not
implement support for
subscriptions
subscription SubscribeToVotes {
newVote {
time,
voter,
value
}
}
Challenges
GraphQL is a new paradigm that offers a lot of new opportunities
for developing performant APIs, but with that comes new
challenges as well.
Challenges when using GraphQL
‣ It’s more complex than RESTful APIs
‣ ORMs are not ready to work performantly with GraphQL (yet)
‣ Caching is a lot more challenging
‣ Application metrics are more complicated
Robert Zhu’s “The Case Against GraphQL” (bit.ly/against-graphql)
GraphQL might not always be the best choice for your API:
consider your use case and the problems you’re trying to solve,
weigh the tradeoffs, and make an informed decision.
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
Tutorial:
slideshare.net/andrewrota/tutorial-building-a-graphql-api-in-php/

More Related Content

What's hot

Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
intelliyole
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
Debasish Ghosh
 
ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
Masatoshi Tada
 
Laravelの検索機能の実装方法
Laravelの検索機能の実装方法Laravelの検索機能の実装方法
Laravelの検索機能の実装方法
yoshitaro yoyo
 
Intro GraphQL
Intro GraphQLIntro GraphQL
Intro GraphQL
Simona Cotin
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Rodrigo Prates
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Fabio Collini
 
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
Edureka!
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
Alexey Soshin
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
Stamatis Zampetakis
 
GraphQL
GraphQLGraphQL
Testing in airflow
Testing in airflowTesting in airflow
Testing in airflow
Chandulal Kavar
 
읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다
wonmin lee
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
Yung-Yu Chen
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
Debasish Ghosh
 
Cucumber and Spock Primer
Cucumber and Spock PrimerCucumber and Spock Primer
Cucumber and Spock Primer
John Ferguson Smart Limited
 
Functional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingFunctional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modeling
Debasish Ghosh
 
Use case and integration of ClickHouse with Apache Superset & Dremio
Use case and integration of ClickHouse with Apache Superset & DremioUse case and integration of ClickHouse with Apache Superset & Dremio
Use case and integration of ClickHouse with Apache Superset & Dremio
Altinity Ltd
 
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
luisw19
 

What's hot (20)

Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
 
ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
 
Laravelの検索機能の実装方法
Laravelの検索機能の実装方法Laravelの検索機能の実装方法
Laravelの検索機能の実装方法
 
Intro GraphQL
Intro GraphQLIntro GraphQL
Intro GraphQL
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
PySpark Programming | PySpark Concepts with Hands-On | PySpark Training | Edu...
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
 
Fungsi-Fungsi PHP
Fungsi-Fungsi PHPFungsi-Fungsi PHP
Fungsi-Fungsi PHP
 
GraphQL
GraphQLGraphQL
GraphQL
 
Testing in airflow
Testing in airflowTesting in airflow
Testing in airflow
 
읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
 
Cucumber and Spock Primer
Cucumber and Spock PrimerCucumber and Spock Primer
Cucumber and Spock Primer
 
Functional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingFunctional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modeling
 
Use case and integration of ClickHouse with Apache Superset & Dremio
Use case and integration of ClickHouse with Apache Superset & DremioUse case and integration of ClickHouse with Apache Superset & Dremio
Use case and integration of ClickHouse with Apache Superset & Dremio
 
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
 

Similar to Performant APIs with GraphQL and PHP (Dutch PHP 2019)

Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHP
Andrew Rota
 
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
MongoDB
 
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
 
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
Nikolas Burk
 
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
QAware GmbH
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Michel Schudel
 
Graphql usage
Graphql usageGraphql usage
Graphql usage
Valentin Buryakov
 
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Codemotion
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
Nikolas Burk
 
Next-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and PrismaNext-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and Prisma
Nikolas Burk
 
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
Pavel Chertorogov
 
GraphQL
GraphQLGraphQL
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in PythonPiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
Serverless GraphQL with AWS AppSync & AWS Amplify
Serverless GraphQL with AWS AppSync & AWS AmplifyServerless GraphQL with AWS AppSync & AWS Amplify
Serverless GraphQL with AWS AppSync & AWS Amplify
Kentucky JavaScript Users Group
 
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
 
OpenDaylight and YANG
OpenDaylight and YANGOpenDaylight and YANG
OpenDaylight and YANG
CoreStack
 
PHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generation
Alexander Obukhov
 
Serverless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersServerless GraphQL for Product Developers
Serverless GraphQL for Product Developers
Sashko Stubailo
 
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
Connected Data World
 
Overview of GraphQL & Clients
Overview of GraphQL & ClientsOverview of GraphQL & Clients
Overview of GraphQL & Clients
Pokai Chang
 

Similar to Performant APIs with GraphQL and PHP (Dutch PHP 2019) (20)

Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHP
 
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
 
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
 
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
 
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
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
Graphql usage
Graphql usageGraphql usage
Graphql usage
 
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
 
Next-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and PrismaNext-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and Prisma
 
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
 
GraphQL
GraphQLGraphQL
GraphQL
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in PythonPiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
 
Serverless GraphQL with AWS AppSync & AWS Amplify
Serverless GraphQL with AWS AppSync & AWS AmplifyServerless GraphQL with AWS AppSync & AWS Amplify
Serverless GraphQL with AWS AppSync & AWS Amplify
 
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...
 
OpenDaylight and YANG
OpenDaylight and YANGOpenDaylight and YANG
OpenDaylight and YANG
 
PHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generation
 
Serverless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersServerless GraphQL for Product Developers
Serverless GraphQL for Product Developers
 
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
 
Overview of GraphQL & Clients
Overview of GraphQL & ClientsOverview of GraphQL & Clients
Overview of GraphQL & Clients
 

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 2019
Andrew 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 performance
Andrew 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 Web
Andrew 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 Application
Andrew Rota
 
Effectively Monitoring Client-Side Performance
Effectively Monitoring Client-Side PerformanceEffectively Monitoring Client-Side Performance
Effectively Monitoring Client-Side Performance
Andrew Rota
 
UI Rendering at Wayfair
UI Rendering at WayfairUI Rendering at Wayfair
UI Rendering at Wayfair
Andrew 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.js
Andrew Rota
 
Tungsten.js: Building a Modular Framework
Tungsten.js: Building a Modular FrameworkTungsten.js: Building a Modular Framework
Tungsten.js: Building a Modular Framework
Andrew Rota
 
Why Static Type Checking is Better
Why Static Type Checking is BetterWhy Static Type Checking is Better
Why Static Type Checking is Better
Andrew 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 Own
Andrew 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 Components
Andrew 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 Combination
Andrew Rota
 
Bem methodology
Bem methodologyBem methodology
Bem methodology
Andrew Rota
 
Web Components and Modular CSS
Web Components and Modular CSSWeb Components and Modular CSS
Web Components and Modular CSS
Andrew 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

Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

Performant APIs with GraphQL and PHP (Dutch PHP 2019)

  • 1. Performant APIs with GraphQL and PHP @AndrewRota | Dutch PHP Conference 2019
  • 2. APIs are important Native Mobile Apps Web browsers (http 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 Traditional APIs ‣ 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": "Dutch PHP 2019", "dates": "June 6-8, 2019" } ]
  • 11. { conferences { name speakers { name twitter } } } { "conferences": [ { "name": "Dutch PHP 2019", "speakers": [ { "name": "Andrew Rota", "twitter": "https://twitter.com/andrewrota" } ] } ] }
  • 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 } } query 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 resources query { conferences { name speakers { name } } } sub-selection
  • 22. Arguments ‣ You can pass named arguments to each field and nested object. { conference(name: "LonghornPHP") { speakers { name } } } argument
  • 23. Variables ‣ Dynamic values can be passed into queries via variables query SearchConfs($name: String){ conferences(nameFilter:$name) { name } } {"name": "LonghornPHP"}
  • 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. Lokka a simple graphql client library ‣ Lokka 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. Apollo complete data management solution ‣ Declarative API for queries and mutations ‣ Normalized client-side caching ‣ Combine local and remote data ‣ Pagination, error handling, refetching, and optimistic UI ‣ Client libraries for popular frontend frameworks (React.js, Angular, Vue), as well as native Android and iOS applications <Query client={client} query={CONFERENCES_QUERY}> {({ loading, error, data }) => { if (loading) return 'Loading...'; if (error) return `Error!`; return ( <ul> {data.conferences.map(conference => ( <li>{conference.name}</li> ))} </ul> ); }} </Query>
  • 35. GraphQL on the Server
  • 36. 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.
  • 37. Let’s build a GraphQL server in PHP!
  • 38. 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.
  • 39. Create a /graphql endpoint to handle requests, and execute queries
  • 40. Handle queries ‣ Queries are made via HTTP requests to a single endpoint ‣ GraphQL::executeQuery parses, validates, and executes the query $schema = new Schema([ 'query' => Types::query() ]); $result = GraphQL::executeQuery( $schema, $requestData['query'], null, $appContext, (array)$requestData['variables'] ); $output = $result->toArray();
  • 41. Then start with the special root type, Query.
  • 42. Root fields ‣ This root type (Query) has a list of root fields, which are the entry points to the API ‣ Each field has a type, and a resolve method for getting the data use GraphQLTypeDefinitionObjectType; use GraphQLTypeDefinitionType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'message' => [ 'type' => Type::string(), 'resolve' => function () { return 'hello world'; } ], ] ]);
  • 43. Fields can return objects ‣ A field can also return a custom ObjectType, which is a type with its own collection of fields. ‣ It can also return lists of other types $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'conferences' => [ 'type' => Types::listOf(Types::conference()), 'description' => 'Returns conferences', 'resolve' => function() { return DataSource::getConferences(); } ], 'message' => [ 'type' => Type::string(), 'resolve' => function () { return 'hello world'; } ], ] ]);
  • 44. Resolvers ‣ Resolve functions tell the server how to get the data for the field ‣ Resolve function can be implemented however you’d like to get the data: SQL queries, cache, or another API ‣ For scalars, the return value will be the value of the field ‣ For object types, the return value will be passed on to nested fields $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'conferences' => [ 'type' => Types::listOf(Types::conference()), 'description' => 'Returns conferences', 'resolve' => function() { return DataSource::getConferences(); } ], 'message' => [ 'type' => Type::string(), 'resolve' => function () { return 'hello world'; } ], ] ]);
  • 45. ...let’s take a closer look at a resolve function function($root, $args, $context, ResolveInfo $info) { return DataSource::getData($root->id); } root / parent result arguments app context query AST and other meta info
  • 46. Creating a custom ObjectType
  • 47. 1. Define your object type 2. Add it to a new field 3. Write the field resolver function
  • 48. Custom object type ‣ Just like the root query type, a custom type is a collection of fields, each with their own types $config = [ 'name' => 'Conference', 'fields' => [ 'name' => Type::nonNull(Types::string()), 'url' => Type::nonNull(Types::string()), 'location' => Types::string(), ] ];
  • 49. Custom object type ‣ Just like the root query type, a custom type is a collection of fields, each with their own types ‣ Fields on a type can also have custom ObjectTypes $config = [ 'name' => 'Conference', 'fields' => [ 'name' => Type::nonNull(Types::string()), 'url' => Type::nonNull(Types::string()), 'location' => Types::string(), 'speakers' => [ 'type' => Types::listOf(Types::speaker()), 'resolve' => function($root) { return DataSource::getSpeakersAtConf($root->id); } ] ] ];
  • 50. And now we have a GraphQL server!
  • 52. 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 } ] } ] } } }
  • 53. GraphiQL - in browser IDE for exploring GraphQL
  • 54. Graphql Playground - like GraphiQL, but more features
  • 55. Voyager - Any GraphQL API as an interactive graph
  • 56. PHPStorm JS GraphQL Plugin - IDE Integration
  • 57. Types can be used in client-side code ‣ If you’re using a client-side language that supports types, you can generate types for graphql queries automatically from the GraphQL schema using tools such as Apollo Codegen ‣ Examples: TypeScript, FlowType, or Swift (iOS)
  • 59. 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 } } }
  • 60. Solution: deferred resolvers ‣ graphql-php provides Deferred objects 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); }); }
  • 61. Limiting Query Complexity and Depth ‣ graphql-php provides a method to calculate and limit the complexity of any query, based on the sum of complexity scores set per field ‣ You can also limit the nested fields requested in queries
  • 62. 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:
  • 63. Subscriptions Client Server Subscribe to an event ‣ GraphQL subscriptions push data to the client when events happen, usually over a long-lived WebSocket connection. ‣ graphql-php does not implement support for subscriptions subscription SubscribeToVotes { newVote { time, voter, value } }
  • 65. GraphQL is a new paradigm that offers a lot of new opportunities for developing performant APIs, but with that comes new challenges as well.
  • 66. Challenges when using GraphQL ‣ It’s more complex than RESTful APIs ‣ ORMs are not ready to work performantly with GraphQL (yet) ‣ Caching is a lot more challenging ‣ Application metrics are more complicated Robert Zhu’s “The Case Against GraphQL” (bit.ly/against-graphql)
  • 67. GraphQL might not always be the best choice for your API: consider your use case and the problems you’re trying to solve, weigh the tradeoffs, and make an informed decision.
  • 68. GraphQL makes it easier to make more efficient queries between your client and your server.
  • 69. GraphQL provides new ways to think about your APIs and the structure of your application’s data.
  • 70. Give it a try!
  • 72. Andrew Rota @AndrewRota Resources ‣ graphql.org ‣ github.com/webonyx/graphql-php ‣ github.com/chentsulin/awesome-graphql ‣ Howtographql.com Tutorial: slideshare.net/andrewrota/tutorial-building-a-graphql-api-in-php/