Challenges with REST API
REST api tend to multiplicate rapidly as complexity of application grows.
For example, an online course consists of multiple modules. To understand necessity of a graphQL course, one can have question- “why-use-graphql”.
- linkedin learning webpage for learning-graphql course answers this question in a module. And, module is made available at an endpoint having following REST URL:
linkedin.com/learning/learning-graphql/why-use-graphql - Now, seperate requests
learningandlearning-graphqlare required to finally reach endpointwhy-use-graphql - As complexity of queries increases, speed of resolution of REST request increases. We can imagine a scenario 1000x complicated in fields like finance, medical, aviation.
Merits of GraphQL
- GrapgQL define shape[i.e. objects and fields] of data and call for it once.
- E.g. While For UI requests, components can be popualated with data and only called once.
- Backward compatibility allows to add new fields to server without breaking existing clients.
- GraphQL wraps around existing APIs. And, It can be constructured in any language.
Structure of GraphQL
Fields and Types
- GraphQL API defines a schema denoting
Fields[returned Objects] andTypes[data Type of the field].
Each field in defined query allows specific data type from Integer, Float, Boolean, Strings, Enum, Null, List, Object. - Like REST endpoints, query fields take arguments. If
valueis mandatory ofor arguments, then!mark is added to denote it. - GraphQL is self documenting, hence documentation is created automatically when schema is defined.
Aliases - Alias gives customised name to fields. So, same field can be queried with different arguments without argument conflict.
FragmentFragments are reusable sets of fields. Alike functions, fragments make it easier to call recurring fields. e.g. Front end components that use same data
Multiple Nested Fields
Pagination
GraphQL operations
Operation name
Assigning discriptive name to query makes it reusable and trackable.
Variables
Set variables which can be passed flexibly to operational queries. This makes operational queries dynamic.
Mutation
Data modifications [Alike PUT and DELETE requests in REST] are called mutations in GraphQL. GraphQL changes dataset behind schema on a valid mutation.
- API defines mutations and schema defined like queries
- Instead of putting data enroute, it is sent as payload in mutation.