SlideShare ist ein Scribd-Unternehmen logo
1 von 72
Downloaden Sie, um offline zu lesen
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/

Weitere ähnliche Inhalte

Was ist angesagt?

Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principlesSanjoy Kumar Roy
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / conceptsPatrick Savalle
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type scriptRemo Jansen
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessibleVictor Trakhtenberg
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHPAdam Culp
 
Top 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaTop 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaEdureka!
 
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...Edureka!
 

Was ist angesagt? (20)

Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Angular
AngularAngular
Angular
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principles
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / concepts
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessible
 
Refactoring PHP
Refactoring PHPRefactoring PHP
Refactoring PHP
 
Top 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaTop 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | Edureka
 
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
 

Ähnlich wie Performant APIs with GraphQL and PHP (Dutch PHP 2019)

Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHPAndrew Rota
 
Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHPAndrew Rota
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPAndrew 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, & TypeScriptMongoDB
 
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
 
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
 
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
 
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
 
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 2017Codemotion
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchNikolas 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 PrismaNikolas 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 serverPavel Chertorogov
 
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 PythonMax Klymyshyn
 
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 YANGCoreStack
 
PHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationAlexander Obukhov
 
Serverless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersServerless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersSashko Stubailo
 

Ähnlich wie Performant APIs with GraphQL and PHP (Dutch PHP 2019) (20)

Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
 
Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHP
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 

Kürzlich hochgeladen (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 

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/