What Is GraphQL and How It Works

0

Well, most of you who are already working in Software Industry may have heard the latest technology  called GraphQL. So today we will try to delve into what is GraphQL and its usage and what problem is it trying to solve.

GraphQL has been here around for some time but it started making some trends recently after Netflix has added another Framework called DGS to easily develop GraphQL services.

GraphQL, developed by Facebook in 2012 and made open to public in 2015, has really changed the way APIs are designed and consumed.

If you are working in Java ecosystem like me from quite long time, working with REST API's is inevitable part of our development journey.

With introduction of Spring framework and especially Spring Boot has been a defacto framework for developing REST API's. While traditional REST APIs have served us well for many years, the emergence of GraphQL has sparked interest due to its ability to address common issues associated with REST.

If you’re just starting with GraphQL, this guide will introduce its core concepts and explain the problems it is trying to solve.

What is GraphQL:

GraphQL is a query language for APIs and a runtime for executing those queries with your existing data.

Unlike REST, where you often interact with multiple endpoints with defined schema, GraphQL allows you to fetch data from a single endpoint, making the API simpler and more flexible. With GraphQL, clients can specify exactly what data they need, reducing the amount of unnecessary data transfer. This unique feature of requesting only the necessary data is a game-changer for many applications, especially those with complex data relationships or dynamic frontend needs.


GraphQL

Key Components of GraphQL:

Before you start using GraphQL, you need to understand some base concepts to really make use of the feature that GraphQL offers.

1. Schema:

Schema is at the heart of every GraphQL API. If you have used Swagger to document Rest API, GraphQL schema will be easier to corelate. In GraphQL schema you clearly define the structure of the data that you will get in response as well as in Input for your different CRUD operations. The schema also ensures some level of type safety validations through different inbuilt types like ID, String or UUID.
So similar to Swagger,  GraphQL schema serves as a reliable blueprint for developers and consumers to understand and predict the data available.

Sample Schema :

  type Product {
    id: ID
    name: String
    description: String
    price: Float 
}

type Query {
    getProduct(id:ID) : Product
    getAllProducts: [Product]
}

input ProductInput {
    id: ID
    name: String
    description: String
    price: Float 
}

type Mutation {
    createProduct(input: ProductInput): Product
    updateProduct(input: ProductInput): Product
    deleteProduct(id:ID!): String
}

2. Queries:

Queries are how you request data from a GraphQL API.

In REST API, We need to define different API's to request different Set of data. Also if the client wants another property, the backend API needs to add it which needs development and a build cycle.

GraphQL consolidates data fetching into one query, and the client specifies exactly what they need.

So lets say one client only wants two properties it request two. if another client wants three properties it can add it in the request and the GraphQL server will provide the relevant data.

  getProduct(id: $productId) {
    id
    name
    quantity
  }

  // another client needs price and category
 getProduct(id: $productId) {
    id
    name
    price
    category
  }
Both of these api calls will be served by single GraphQL api and you don't need to create separate endpoint like REST.

Well some people might argue what about the Creating or updating Product details, How should we do it?  The answer is Mutations.

Mutations:

While queries fetch data, mutations are used to modify it. This could include creating, updating, or deleting data.

Mutations in GraphQL are similar to POST, PUT, or DELETE operations in REST. By using mutations, clients can safely change data within the application without impacting the overall structure of queries.

Mutation ( generated using DALL-E)
 

Create Product:

  mutation {
  createProduct(input: {
    id: "00a3b831-5dba-4823-b486-fa48d73fbf87",
    name: "NewCompany Laptop",
    description: "laptop with I7 processor",
    price: 2333.45
  }) {
    id
    name
    price
  }
}

Update Product:

  mutation {
  updateProduct(input: {
    id: "00a3b831-5dba-4823-b486-fa48d73fbf87",
    name: "NewCompany Laptop",
    description: "laptop with I7 processor",
    price: 2333.45
  }) {
    id
    name
    price
  }
}

Delete Product:

  mutation {
  deleteProduct(id: "00a3b831-5dba-4823-b486-fa48d73fbf87")
}

Subscriptions:

Subscriptions is great feature where the server wants to push the event back to client if there is any new data available. This can be useful to develop chat application. They allow the server to push updates to the client when specific events occur, instead of requiring the client to continuously poll the server for changes.

Lets say you want to showcase a live data feeds of share market prices or sports match score updates, GraphQL subscriptions can play important role in developing this kind of use cases.

How subscription works?

  1. GraphQL client sends a subscription request
  2. Server maintains a open connection with client( usually through WebSocket)
  3. Server sends updates whenever new data or event occurs.

Conclusion:

In this article, we explored the what GraphQL is and it fundamental concepts like schema, query, mutations and subscriptions. In the upcoming series I will write about how we can implement GraphQL in real world project.

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*

Cookies Consent

This website uses cookies to offer you a better Browsing Experience. By using our website, You agree to the use of Cookies

Privacy Policy