Using GraphQL we can send a request to the one endpoint, which has methods to return what you need depending on your query.
The query may look like this:
With the REST API you need to send requests from the client to multiple endpoints to collect users, posts, and comments. GraphQL is a powerful query language allows us to use one endpoint to collect all this information from the server. Another cool feater is that you can control what to get with API and what do not.
For example, I can add field author to the book, by just simply adding the author to my query. Look in the below example.
Very easy and cool right?!
Let’s start with the installation part, to prepare our machine for coding with Node.js using the Express framework and GraphQL.
Installation necessary packages to setup GraphQL, Node.js and Express:
If you already have installed node just skip these steps!
2. GET package.json
To install package.json, being in the project directory run on your terminal:
3. EXPRESS — Express is a Node.js web application framework
Installing express, run on your terminal:
npm install express — save
4. NODEMON — to listen for any changes in any file in the project
Installing nodemon globaly on your computer, run on your terminal:
npm install nodemon -g
Installing graphql, run on your terminal:
npm install graphql
6. EXPRESS-GRAPHQL— for Express to understand GraphQL
Installing graphql-express, run on your terminal:
npm install express-graphql
What is type in GraphQL?
GraphQL service defines a set of types that describe the set of possible data you can query on that service.
For example, we have books and authors. To be able to get the data as an API to the client we need to create BookType and AuthorType. We setting fields that we have for the book and author.
You can implement GraphQL Types as shown below:
What are root queries are and how we define them?
Also, GraphQL provides us optional feature Graphiql to test our API.
Now when you request the ‘/graphql’ you can see Graphiql UI.
To test our API we need to send a request with a query, it is very simple.
As you can see our query has an argument to get the author by id (id: “1”).
On the right of the screen, you can see fields that you have access to get data.
These are just basics of using GraphQL, you can find more information on the resources provided below. Take care and be safe!