Friday, March 12, 2021

Introduction to GraphQL - Part 1

Introduction to GraphQL


GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.

A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type. For example, a GraphQL service that tells us who the logged in user is (me) as well as that user's name might look something like this:

type Query {
  meUser
}
 
type User {
  idID
  nameString
}

Functions for each field for each type:

function Query_me(request) {
  return request.auth.user;
}
 
function User_name(user) {
  return user.getName();
}

The running service can receive GraphQl query to validate and execute. A received query is first check it refers to the types and fields defined and then runs the provided function to produce result.

Query:

{
  me {
    name
  }
}

Result:
 
{
  "me"{
    "name""Vishal Patil"
  }
}

To understand further - GraphQL over HTTP
Check out the diagram below, to get a sense of how GraphQL is typically used in your stack:


As you can see we only need a single query in order to get information it need. We don’t need to burden the sever with multiple requests.

GraphQL client-server flow:
  • Note that the GraphQL query is not really JSON; it looks like the shape of the JSON you want. So when we make a 'POST' request to send our GraphQL query to the server, it is sent as a "string" by the client.
  • The server gets the JSON object and extracts the query string. As per the GraphQL syntax and the graph data model (GraphQL schema), the server processes and validates the GraphQL query.
  • Just like a typical API server, the GraphQL API server then makes calls to a database or other services to fetch the data that the client requested.
  • The server then takes the data and returns it to the client in a JSON object.

GraphQL Schema
  • GraphQL user schema to describe the shape of data
  • Schema defines a hierarchy of types with fields that are populated from backend
  • Schema specifies which queries or mutations available for client to execute against the data
  • Schema defines the collection of types and relationship between those types

In the below example, every book has an author and every author has a list of books.

type Book {
    titleString
    authorAuthor
}

type Author {
    nameString
    books[Book]
}


Supported Types

Every type definition in GraphQL schema belong to one of the following categories

  • Scalar types
  • Object types
  • The Query type
  • The Mutation type
  • Input types
Scalar Types

Scalar types are similar to primitive data types in any programming language
  • Int: A signed 32‐bit integer.
  • Float: A signed double-precision floating-point value.
  • String: A UTF‐8 character sequence.
  • Boolean: true or false.
  • ID (Serialized as String): The ID scalar type represents a unique identifier

Object Type

Most of the types we define in a GraphQL schema are object types. An object type contains a collection of fields, each of which can be either a scalar type or another object type.

The two types of allowed operations in GraphQL are queries and mutations. 
  • Queries – operates like a GET
  • Mutations – operates like POST/PATCH OR UPDATE/DELETE

Queries
Queries return only the data user specify. To form a query user must specify fields within fields (nested fields)

Query Overview
The Query defines all of the top-level entry points for queries that clients execute against data. Query is interactive in nature. User can limit or add more variables to a query at any time to get the desired result

#syntax 1

query {
  JSON objects to return
}

#Example:

query Employees {
  Employees {
    name
    Employers {
      name
    }
  }
}



Mutations
To form a mutation  three things are needed 
  • Mutation Name
    • Type of modification
  • Input Object
    • Data want to sent to the server. Normally it passed as an argument to the mutation name
  • Payload Object
    • Data return from the server. Passed as a body to the mutation.
Mutation Overview
Mutations are structured like this:

type MutationResponse { 
  statusString!
}

type PassengerData {
  nameString! 
  ageString! 
  addressString!
}

type Mutation {
  createPassenger(passengerString )MutationResponse 
}

 #String is nothing but PassengerData

# Query in Frontend looks like:
mutation PassengerMutation($passengerPassengerData! ) {
  createPassenger(passenger$passenger) { 
    status
  }
}


    Note: The scalar type “!” mark indicates the field is required.


Working with variables:

Variables can make queries more dynamic and powerful, and they can reduce complexity when passing mutation input objects.
 
Three ways using  a variable
  • Define outside of the operation in a object
  • Pass the variable to the operation as an argument
  • Use with in operations.

Examples:


type MutationResponse { 
  statusString!
}

type PassengerData {
  nameString! 
  ageString! 
  addressString!
}


To understand more about GraphQL please refer the below links

  • https://graphql.org/learn/ 
  • https://www.tutorialspoint.com/graphql
  • https://developer.github.com/v4/guides/intro-to-graphql/

No comments:

Post a Comment