How to use a graphql API from a headless cms
Data fetching has been an extremely crucial part of every headless CMS. It is the core concept on which a headless CMS works. It allows the users to fetch saved data and then integrate their preferred frontend technology to create the desired user-interface for their website.
There are many ways or methods available to fetch data from the backend APIs. Most of the data fetching methods fetch all the data from APIs. This whole fetched data contains a large amount of unnecessary data and then we have to filter out the required data.
On small projects, this extra fetched data does not make any significant difference. But suppose the fetched data is in millions and trillions, in this case, fetching of unnecessary data results in slow loading of webpage eventually spoiling the user experience.
That’s where GraphQL becomes our savior. GraphQL makes it possible to fetch only the required data and avoid the fetching of unnecessary data. Let’s discuss GraphQL and understand it's working with the help of some examples.
Introduction to GraphQL
GraphQL is a data query language that allows you to define data fetching queries for each specific data that you want to retrieve from the APIs. With the help of GraphQL API, you can get the specific set of data that we demand for, while preventing the withdrawal of any redundant data.
This ultimately reduces the loading time of webpages resulting in a huge positive impact on user experience. Not just this, the use of GraphQL also enhances the flexibility and user-friendly characteristics of APIs.
GraphQL being a query language, it demands for a query to function and get the data from the database.
Let’s take a look at this at the working of this query –
query MyQuery{
students {
name
age
courses
}
}
In this example, we have used a GraphQL query to get the name, age, and courses of all the students stored in the database. This query will only fetch the name, age, and courses data from the backend API avoiding all other stored data. Here, the query is a built-in keyword and all other mentioned words are the manually defined variables of the query.
Not just the data fetching, GraphQL also comes in handy when you want to store the data in the backend API without disturbing the already stored data. Just like to fetch data query is defined, similarly, query is created to input data in the database.
Now the question arises, from where you can get the details about these data fetching queries? And the answer is GraphQL Schema
Schema
GraphQL Schema is the core reason behind the working of GraphQL queries. Schema is a part of GraphQL where details about all the queries that the user could use on the client-side to get the data and even store the data is present. GraphQL Schema structures the whole shape of the data graph.
In other words, GraphQL Schema can be defined as a collection of types along with their fields and the relationship in-between them.
In GraphQ Schema, you can get the information of every query that you can execute whether it’s a query to fetch data or to input data. Not just this, Schema file also tells you what type of data you will get on running a specific data fetching query.
Every query present in GraphQL Schema is made up of some in-built types with manually defined variables. Every query whether it is to input data, fetch data, and perform some other operations on data is combination of built-in type and variables. Let’s take a look at them
Type
Object types are the most basic components of GraphQL Schema. In GraphQL Schema, we can define queries in the form of objects along with the key and value pairs that we can fetch and store in the APIs.
Let’s take a look at an example –
type student {
id: ID
name: String
age: Int
course: [String]
}
In this example, type is a pre-defined keyword that signifies the initialisation of a new variable, student is the variable name. In student object, we have assigned some key-value pairs along with the data type of value that each key holds.
If you open the student object, you will get id of type ID, name of type String, age having an integer value, and course storing an array of Strings.
GraphQL schema supports many data-types including Strings, Integer, ID, Boolean, Float, and Object. One thing to note is that, unlike a normal object, you do not have to use any comma sign (,) after each key-value pair. Here, you just go to the next line to define the next key-value pair
Input
Now to store or input the data in the backend API, you have got another type in the GraphQL schema for that as well.
GraphQL Schema comes with the input keyword which is used to create queries to store data in backend API without touching the already stored data. It demands some data from you in the form of a specified type and then store the data in the backend API.
Let’s understand it with the help of an example –
input students {
id: ID
name: String
age: Int
course: [String]
}
The structure of code snippet in this example looks very much similar with the above-explained examples. But the new thing in this example is the input keyword. With the input keyword, this has become an input query which will store the data in the backend API.
When you will run this query, it will demand you to enter some values for all the keys only in the specified data type and then the final data will get stored in the backend API.
The default value of every key is null. So, if the user does not add any value to any key, then it’s value is kept as null.
GraphQL comes with a non-null modifier denoted by the exclamation mark “!”. This modifier prevents the keys from having a null value making it mandatory for the user to add any value to those keys.
Let’s take an example
input students {
id: ID!
name: String
age: Int!
courses: [String]
}
In this example, the students object has id and age key where we have used non-null modifier. So, if you do not give any value to these two keys, then this query will not work.
Query
GraphQL Schema has a query type that basically define queries to fetch data from the backend API. The user can run the query on the client-side to send a fetch data request to the backend server and then the fetched data is returned.
Just like other types explained above, the query type is also initialised in the schema file along with the type of data it will return.
Here’s an example –
query students {
id: ID
name: String
age: Int
course: [String]
}
This query will return the students object and it will contain the values of only id, name, age, and course keys.
You can read the Schema file to get the details of all available queries that you can execute to fetch data.
Variables
Variables are basically the arguments that you can pass in the query to execute that query for different arguments to return different data. The query demands the value of those arguments from the user and then runs considering the passed values. The variable is denoted by the ‘$’ symbol
To use variables in GraphQL queries, it first requires assigning the data-type of the variables initialised in the query.
Let’s take a look at an example –
query fetchStudents($id: ID) {
getStudents (id: $id): students
}
In this example, the fetchStudens query contains a variable $id of data-type ID. When this query will run, it will demand from you to enter the value for $id variable. The entered value will be passed to getStudents function and it will fetch the students data containing that specific id.
In order to avoid a null value in the id variable, the non-null modifier can also be in the arguments to make it mandatory for the users to pass some value in those arguments. Here’s an example of it –
query MyQuery($id: ID!){
getStudents (id: $id): students
}
In this example, to make the MyQuery fetch data, the user has to add some value in the id variable.
Variables comes in very handy when it takes to fetch a specific set of data from a whole collection of data. A variable can work as an identifier given by the user and then fetch data considering that variable. In such way, we can avoid the fetching of unnecessary data.
Mutation
Mutation is a type of query that allows you to modify or manipulate the data stored in the backend API. Mutations fetches the data from API, modifies the data, and then store the updated data. This query can be used to insert, update or delete the stored data.
Every mutation query is initiated with the “mutation” keyword.
Here’s an example:
mutation ($id: ID!, $name: String, $age: Int!, $course: [Strings]) {
addStudent(id: $id, name: $name, age: $age, course: $course) : students
}
In this example, there is a mutation query, having an edit operation addStudent to add a new student. The details required to create a new student are mentioned as arguments/variables. And finally, this mutation query will return an object as students type.
Use of GraphQL in Caisy
Caisy CMS allows you to create custom components and documents to build your website. You can create custom reusable blueprints using multiple content blocks present on the Add fields section to add text, images, videos, numbers, etc. Then use those blueprints to create components and documents for your website.
Caisy is a headless CMS so it chops off the presentation layer from the backend server. Since the presentation layer is absent, so it gives you the freedom to get the data from the backend server and use any frontend technology with fetched data to build the interface. Just fetch the data stored in Caisy server and display it on any digital channel.
Unlike traditional monolithic CMS, headless Caisy CMS prevents the restriction to use a specific frontend technology and developers can integrate any frontend technology without worrying about any negative impact on user-interface.
Every headless CMS comes with a data fetching method to get the data for our use. In Caisy, you get the GraphQL API as the way to interact and access to the data stored on your Caisy dashboard.
We could have used the REST API in Caisy, but the reason for using GraphQL API over traditional REST API is because of it’s several benefits that it offers to the developers. Here are some reasons why we chose GraphQL as a go to method to access Caisy CMS:
Avoid overfetching – In REST API, the data fetched through the endpoints is usually much more than the data actually required by the user, resulting in overfetching. In GraphQL, the user can target the specific details and fields that they want to fetch for their work and the GraphQL API will return only targeted data thus avoiding overfetching.
Easy API Interaction – Unlike REST API, GraphQL has only one end-point “/graphql” which makes it so much easy to interact with the whole GraphQL API. Ultimately, simplifying the whole process of interaction with API for a developer.
Support for different technologies – GraphQL is not restricted to any specific language or technology. Developers can take advantage of any language or framework like ReactJS, NextJS, AngularJS, VueJS, etc to build a user-interface.
Improved Developer Experience – GraphQL comes with an Integrated Development Experience (IDE) named as “GraphiQL” which allows the developers to play around with the queries, schemas, test mutations, and check the real-time documentation. This helps the developers to better understand the working of queries and improve the API-related queries.
Flexible API – GraphQL API happily accepts any changes. You can add any new types or fields without disturbing the existing clients. This makes it possible to update the API by adding new fields avoiding the need to create a new API from scratch everytime for any new query.
Validation of types – Schemas works as the main structure of GraphQL API. The type of data we can fetch, queries we can run, everything is defined in the Schema file. This schema file performs validation by allowing only those types of data to get fetched which are defined in the Schema file.
Fetch from multiple sources – GraphQL comes with the flexibility to ask for data from multiple sources at once. With the help of resolvers, the server is allowed to fetch and return data from multiple sources in a single query, eventually improving the performance.
All these benefits of GraphQL are the reason why we integrated GraphQL API in Caisy CMS to fetch data. In Caisy CMS, you do not need to create a Schema file from scratch. Caisy is smart enough that it automatically generates a Schema file depending upon the components and documents you have created in your project.
There is a “playground” feature available on the left sidebar menu. In this feature, you can see all the available GraphQL options like queries, mutations, variables, and other things to experiment with them and test them.
You can also get the GraphQL endpoint at playground to connect your project with Caisy CMS.
In the Playground feature, there is an “Explorer” tab where you can select the fields of whose data you want to fetch and it will automatically generate a query for it.
All the components and documents you have created in your project will be listed in the Explorer tab along with all their respective details. Just simply select your desired fields and their details and a query to fetch all that data will be automatically generated side-by-side.
Not just the available queries, you can also see there’s a “Documents” tab and a “History” tab. In the Documents, all the queries generated via Schema file will documented. You can read it and understand what query will return what type of data.
History tab will give you the record of all the queries that you have created manually in the playground. The queries you create get saved to History tab so that you can easily access them anytime in the future.
There’s also a “Favorite” section in the History so that you can star mark any query and keep them in Favorite section.
You can also try out the generated query by clicking on Execute button and it will display the data fetched by that query.
You can also select the option to select the arguments or variables that you want to include in the query and then pass the values of those variables in the “Variables” tab.
You can also play around with the headers property of the your GraphQL query as there is an dedicated “Headers” tab given along side with the Variables tab.
That’s how you can create queries in the Caisy CMS and then use those queries in your project to fetch data and use it.