Site icon apilayer Blog

How to Get Started with GraphQL and Node.js

Hexagon

Today, most of the applications that serve the open world such as the Web and mobile use web services. A web service written on the backend of applications simultaneously supports the application’s frontend, mobile applications, and even IoT devices if any. This increase in its use has created some problems and needs. As a solution to many of these needs, Facebook announced and launched GraphQL in 2015.

What is GraphQL

Since my main purpose in this article is not to explain GraphQL, I will explain it with a basic sentence or two and move on to Graphql integration with Nodejs, which is our main topic.

In simple terms, GraphQL is a query technology that we can perform operations such as data extraction, querying, adding, updating. In short, the biggest advantage of Rest API is that it enables the client side to access the data they need directly without receiving any other data. In this way, the client side is not overwhelmed with unnecessary data and we gain an advantage in traffic.

Integration GraphQL to Nodejs 

Before moving on to the example, let’s start by assuming that you have Node installed on your computer.

We open a folder in any file path and run these commands in order in this folder.

Then let’s open the application with a code editor and create a file named server.js in this file path. Now let’s paste the following codes into the server.js file.

With the code we wrote, a Graphql Schema was created with the Student model. Student model includes id, name, surname, school_number fields. No database was used in the application, instead a json list was preferred for practicality.

Let’s run the application with the following command.

After the application is running, let’s go to the following url from a web browser.

The Graphiql interface, which is a Graphql plugin, welcomes us. With this interface, we can easily perform our tests.

For example, the query we added in the picture below was prepared and run.

Since name and school_number fields are specified by the client for the Student model, only the name and school_number fields of the record belonging to the relevant id were obtained as a result of the query. This is one of the most important features that distinguish GraphQL from Rest API.

Conclusion

GraphQL is a very successful query language that allows us to do many operations with a single query. It does not bring all the data from the database and present the fields we specified in it. Whatever we write on the Query side, it brings that part and presents it to us. Therefore, it provides a faster and more flexible structure compared to REST APIs.

 

Exit mobile version