Introduction To GraphQL¶

In Association With Spilberg

👨‍💻 Gaurav Sehrawat¶

🕸Full Stack Developer¶

💻 Dimebox/Verifone¶

Github: igauravsehrawat¶

Twitter: root3d¶

Not just GraphQL, but also the implementation. Seeing the code

What is GraphQL?¶

show off hands

talkStructure {
    'What is GraphQL?',
    'Design Principle of GraphQL.',
    'Comparison with Rest',
    'GraphQL specs',
    'GraphQL tools',
    'Our Tech Stack',
    'Building an API on backend',
    'Consuming API on frontend'
}

What is GraphQL?¶

GraphQL is a query language designed to build client applications by providing an intuitive¶

and flexible syntax¶

and system for describing their data requirements and interactions¶

Or Should I say Graph Cool¶

being-cool

Design Principles Of GraphQL¶

Hierarchical¶

Product‐centric¶

Strong‐typing¶

Client‐specified queries¶

Introspective¶

Hierarchical: Most product development today involves the creation and manipulation of view hierarchies. To achieve congruence with the structure of these applications, a GraphQL query itself is structured hierarchically. The query is shaped just like the data it returns. It is a natural way for clients to describe data requirements.

Product‐centric: GraphQL is unapologetically driven by the requirements of views and the front‐end engineers that write them. GraphQL starts with their way of thinking and requirements and builds the language and runtime necessary to enable that.

Strong‐typing: Every GraphQL server defines an application‐specific type system. Queries are executed within the context of that type system. Given a query, tools can ensure that the query is both syntactically correct and valid within the GraphQL type system before execution, i.e. at development time, and the server can make certain guarantees about the shape and nature of the response.

Client‐specified queries: Through its type system, a GraphQL server publishes the capabilities that its clients are allowed to consume. It is the client that is responsible for specifying exactly how it will consume those published capabilities. These queries are specified at field‐level granularity. In the majority of client‐server applications written without GraphQL, the server determines the data returned in its various scripted endpoints. A GraphQL query, on the other hand, returns exactly what a client asks for and no more.

Introspective: GraphQL is introspective. A GraphQL server’s type system must be queryable by the GraphQL language itself, as will be described in this specification. GraphQL introspection serves as a powerful platform for building common tools and client software libraries.

A query language for your API¶

But what is query language?¶

It is literally a query*¶

Comparison With REST APIs¶

https://twitter.com/nikkitaftw/status/1011928066816462848?lang=en Image @nikkitaftw

https://twitter.com/peggyrayzis/status/1011981410465468416 Image @peggyrayzis

Documentation is self sustained.¶

What changes with GraphQL?¶

Your BFF remains same irrespective of frontend¶

* BFF - Backend For Frontend¶

📱Mobile¶

🖥Website¶

iOS¶

Android¶

And more¶

Same BFF¶

GraphQL is language indepedent, it has the specification and languages impelement them¶

So what is there in GraphQL specs?¶

Query¶

Mutation¶

Subscriptions¶

Query¶

Think of it as data fetching APIs¶

How does it look like?¶

query {
  items {
    id
    title
    description
    image
    price
  }
}

Mutation¶

Think of it as data insertion APIs¶

How does it look like?¶

mutation createItem {
  createItem(
    title: "Google Logo",
    description: "Logo description",
    image: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
    largeImage: "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
    price:1000
  ) {
    id
    title
  }
}

Subscriptions¶

Think of it as websockets with real time data¶

subscriptions example

TypeDefinition¶

ScalarTypeDefinition¶

ObjectTypeDefinition¶

InterfaceTypeDefinition¶

UnionTypeDefinition¶

EnumTypeDefinition¶

InputObjectTypeDefinition¶

Enum Type¶

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

Interface¶

interface Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
}

Union Type¶

union SearchResult = Human | Droid | Starship

Input Type¶

input ReviewInput {
  stars: Int!
  commentary: String
}

Using it like

mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
  createReview(episode: $ep, review: $review) {
    stars
    commentary
  }
}

The fundamental unit of any GraphQL Schema is the type. There are six kinds of named type definitions in GraphQL, and two wrapping types.

The most basic type is a Scalar. A scalar represents a primitive value, like a string or an integer. Oftentimes, the possible responses for a scalar field are enumerable. GraphQL offers an Enum type in those cases, where the type specifies the space of valid responses.

Scalars and Enums form the leaves in response trees; the intermediate levels are Object types, which define a set of fields, where each field is another type in the system, allowing the definition of arbitrary type hierarchies.

GraphQL supports two abstract types: interfaces and unions.

An Interface defines a list of fields; Object types that implement that interface are guaranteed to implement those fields. Whenever the type system claims it will return an interface, it will return a valid implementing type.

A Union defines a list of possible types; similar to interfaces, whenever the type system claims a union will be returned, one of the possible types will be returned.

Finally, oftentimes it is useful to provide complex structs as inputs to GraphQL field arguments or variables; the Input Object type allows the schema to define exactly what data is expected.

Introspection¶

A GraphQL server supports introspection over its schema. This schema is queried using GraphQL itself, creating a powerful platform for tool‐building.

Validation¶

GraphQL does not just verify if a request is syntactically correct, but also ensures that it is unambiguous and mistake‐free in the context of a given GraphQL schema.

An invalid request is still technically executable, and will always produce a stable result as defined by the algorithms in the Execution section, however that result may be ambiguous, surprising, or unexpected relative to a request containing validation errors, so execution should only occur for valid requests.

Execution¶

GraphQL generates a response from a request via execution.

A request for execution consists of a few pieces of information:

The schema to use, typically solely provided by the GraphQL service. A Document which must contain GraphQL OperationDefinition and may contain FragmentDefinition. Optionally: The name of the Operation in the Document to execute. Optionally: Values for any Variables defined by the Operation. An initial value corresponding to the root type being executed. Conceptually, an initial value represents the “universe” of data available via a GraphQL Service. It is common for a GraphQL Service to always use the same initial value for every request.

Response¶

When a GraphQL server receives a request, it must return a well‐formed response. The server’s response describes the result of executing the requested operation if successful, and describes any errors encountered during the request.

A response may contain both a partial response as well as encountered errors in the case that a field error occurred on a field which was replaced with null.

A GraphQL Document describes a complete file or request string operated on by a GraphQL service or client. A document contains multiple definitions, either executable or representative of a GraphQL type system.

thats enough

Practical Stuff¶

graphql-playground

Apollo Extension¶

Demo, Demo, Demo¶

show-me-code

Remember? GraphQL is langauge independent! But fundamentals remains same.¶

In general, you will need¶

Frontend/UI GraphQL Frontend Data Management GraphQL Server Database ORM
Frontend rendering Performing GraphQL mutation Implementing Query and Mutation resolvers Provding a set of GraphQL CRUD APIs for MySQL, Postgres, MongoDB etc
Styling Fetching GraphQL Queries Custom server side logic Schema Definition
Testing frontend Caching GraphQL Data Authentication Data relationships

Our Tech Stack In Javascript¶

React/Next.js

Apollo

GraphQL Yoga

Prisma

React/Next.js¶

A JavaScript library for building user interfaces¶

ServerSide rendering, PWA, Mobile Apps, Desktop Apps, Static websites

Apollo¶

Apollo Client is a complete state management library for JavaScript apps.¶

Show the extension¶

GraphQL Yoga¶

graphql-yoga is like create-react-app for building GraphQL servers.¶

Show the GraphQL Playground¶

Prisma¶

Prisma replaces traditional ORMs and simplifies database workflows:¶

Access:¶

Migrate¶

Manage:¶

Access: Type-safe database access with the auto-generated Prisma client (in JavaScript, TypeScript, Go) Migrate: Declarative data modelling and migrations (optional) Manage: Visual data management with Prisma Admin

Let's dive into code¶

Let's do a basic(101) Query in GraphQL¶

Backend Data definition¶

data model layer

    • Prisma definition

Model definition is nearly same there are some utilities provided by the abstraction layer.

Backend GraphQL Server¶

GraphQL Query layer

query layer

Resolvers¶

Whatis Resolver? And Why?¶

Each field on each type is backed by a function called the resolver¶

which is provided by the GraphQL server developer.¶

In order to respond to queries, a schema needs to have resolve functions for all fields. Resolve functions cannot be included in the GraphQL schema language, so they must be added separately. This collection of functions is called the "resolver map".

query resolver layer

What are the arguments?¶

parent(obj)¶

args¶

ctx¶

info¶

obj: The object that contains the result returned from the resolver on the parent field, or, in the case of a top-level Query field, the rootValue passed from the server configuration. This argument enables the nested nature of GraphQL queries. args: An object with the arguments passed into the field in the query. For example, if the field was called with author(name: "Ada"), the args object would be: { "name": "Ada" }. context: This is an object shared by all resolvers in a particular query, and is used to contain per-request state, including authentication information, dataloader instances, and anything else that should be taken into account when resolving the query. If you're using Apollo Server, read about how to set the context in the setup documentation. info: This argument should only be used in advanced cases, but it contains information about the execution state of the query, including the field name, path to the field from the root, and more. It's only documented in the GraphQL.js source code.

Frontend¶

frontend-tools.png

Frontend Querying¶

frontend-querying.png

Frontend Fetching & Rendering¶

frontend-fetching-and-rendering.png

How to start the server?¶

Starting the server

GraphQL Intermediate Walk Through¶

GraphQL 103¶

User Login¶

Code In Editor¶

Live Demo 🔥🔥🔥¶

References & Resources¶

  • https://graphql.github.io/graphql-spec/draft
  • https://github.com/chentsulin/awesome-graphql

HomeWork¶

GraphQL Documentary

GraphQL Documentary

Questions??¶

👨‍💻 Gaurav Sehrawat¶

🕸Full Stack Developer¶

💻 Dimebox/Verifone¶

Github: igauravsehrawat¶

Twitter: root3d¶

Thank you¶