GraphQL: Data in Precise Request
GraphQL
A query language for reading and mutating data in API's along with a type system where one can provide schema for their data.
It's a developer query language in modern world of web.
GraphQL Explorer
GraphQL studio is divided into three sections: Documentation, Operation for performing query, and finally Response window.
REST Architecture
Let's first talk about traditional approach of consuming API's developers use REST architecture (Representational State Transfer for distributed system) wherein data lives on bunch of URLs on server.
REST architecture comes with certain limitations - Under fetching and Over fetching. This requires multiple URLs to fetch data from an API.
Precise Request with GraphQL
To overcome these limitations GraphQL transforms how apps fetch data from an API, helping its users to query exactly what data they need but with a single query.
And not only this GraphQL strong type system helps to define relationships between different data entities across any number of systems.
This entitles its users to focus only on the data needs, what to do with that data without any attention to where its stored. In a nutshell front-end requests for the data need that they want and back-end writes the code to resolve that request.
Client Request Server Resolve
-- query.gql -- response.json
-- JS -- Go, Node etc..
With growing data which we have over servers, databases, at times even a complete organisation is responsible for preserving data. GraphQL excels at working with this ever-growing data by providing a consistent, structured way to tackle this challenge of fetching, organising, and finally working with this data.
One of the biggest benefits that GraphQL provides over similar solutions for querying and mutating data is - it gives its user exactly what they need in a single request.
领英推荐
Wouldn't it be irritating if every time you request for some piece of information and you have to filter out lot of unnecessary information from your response?
Schema, Types & Fields
GraphQL provides solution to this by building a document for our data known as schema. By using this schema one can build requests including specific details we would expect in response and ignoring other unnecessary information.
Schema uses concept of types and field which makes this process of making precise request possible. Types are used to draw boundaries around particular kind of data. Attributes in type are known as fields. GraphQL has two main categories of types - Object Types (represents properties/fields that are to be retrieved) and Scalar Types (describes kind of value each field on object type represents).
Data Read
Every GraphQL has a Query type which is the entry point to read data or consume data from API's.
type Query {
fruits: [Fruit]
seller (id: String!): Seller
}
Data Mutate
There is another type Mutation which is used to write data or modify data on API.
type Mutation {
sellFruit(name: String): Fruit
purchaseFruit(name: String): String
}
Interfaces
They allow to define an object with set of fields that multiple implementing object types have in common. When a field returns an interface we can query any of the fields shared by its implementing types.
interface Producer {
id: ID!
name: String!
quantity: Int
price: Int!
}
type Fruit implements Producer {
# Comments: Implements all fields of interface
id: ID!
name: String!
quantity: Int
price: Int!
""" Multi-Line Description:
Other field(s) of Fruit Type """
isSeedless: Boolean
}
type Vegetable implements Producer {
# Comments: Implements all fields of interface
id: ID!
name: String!
quantity: Int
price: Int!
""" Multi-Line Description:
Other field(s) of Vegetable Type """
vegetableFamily: String
}
type Stall {
id: ID!
name: String!
stallNumber: String!
# Scalar Type - List is represented by []
availableProducer: [Producer]
}
# Querying Interface Producer and accessing other object types:
# fruits, vegetables
query GetPopularStallProducer {
mostPopularStall {
availableProducer {
# Field that tells which object Type: Fruit/Vegetable
__typename
id
name
price
}
}
}
Fragments
In order to query particular field exclusive to particular object type from an interface we can use fragments. Fragments defines set of query fields that can be reused and they can be applied conditionally asking for certain data from particular object type. For e.g. in above example in order to query Fruit type field isSeedless and Vegetable type field vegetable Family we can use inline fragments with spread operator (...) and using keyword 'on' along with object type i.e.
query GetPopularStallProducer {
mostPopularStall {
availableProducer {
__typename
id
name
price
... on Fruit {
isSeedless
}
... on Vegetable {
vegetableFamily
}
}
}
}
Advantages
Reliable: Apps using GraphQL are fast, reliable, stable as they control data that they receive and not the server.
Single Request: It gets all the data that app needs in single request unlike REST APIs that requires loading from multiple URLs. This saves time and bandwidth as it allows making multiple resources request in single query by reducing number of network calls to the server.
Strongly-typed Schema: Its type system helps apps to avoid writing manual parsing code. It also helps to evolve APIs without versions upgrade by adding new fields and types to graphQL API without impacting existing queries.
Versioning Is Not Required: It uses single evolving version concept allowing apps to continuously access new features and encourage cleaner, maintainable code on server.
Should we use GraphQL or other similar solutions - REST, SOAP ?
GraphQL serves as an apt. fit in different scenarios with different requirements. For example for mobile apps where bandwidth usage matters a lot GraphQL can be used. Applications where lot of metadata or nested data needs to be fetch in single call as in different social networking platforms. It can be added as an abstraction layer on existing APIs wherein end-users can specify the structure of response as per business requirement and create customisation response. Applications where we need data fetching control that's one of the core benefits of GraphQL which in turn prevents over-fetching and under-fetching issues. On other hand REST still comes with lot of built-in features like caching, file upload, rate limitation per API key whereas GraphQL need to use third party tools to enable these features. For complex queries REST is still preferred choice by many developers on other side GraphQL nested architecture can turn into bottleneck sometimes. Error Handling is still better with RESTful API's whereas GraphQL status code 200 OK for every request makes it difficult to comprehend for managing errors or use it as monitoring tool. Handling recursion and deep nesting in queries are some improvement areas in progress in GraphQL.