How to build a Graphql API from scratch using Nodejs, Express, and MongoDB
GraphQL is an open-source server-side data query and manipulation language for APIs, and a runtime for fulfilling.
GraphQL is one of the modern ways of building and querying APIS. Graphql server exposes a single endpoint and responds to queries.
GraphQL is a new API standard that provides a more efficient, powerful, and flexible alternative to REST. It allows a client to fetch only the data it needs from a server.
What is GraphQL?
GraphQL is a query language created by “Facebook” with the purpose of building robust client applications based on intuitive and flexible syntax.
GraphQL is a middleware that allows the user to have 1 endpoint to handle most requests on your express server. The benefits of using this:
- Avoids having to create many routes to handle everything.
- Avoids over-fetching and under-fetching data
- This works concurrently with API routes so the server can still be RESTful.
It fully describes the data requirements and interactions with an existing database. GraphQL was developed internally by Facebook and released in 2015.
Uses of GraphQL
Apps for devices such as “Mobile Phones”, “Smartwatches”, and “IoT devices”.
Graphql server has 2 parts that determine how it works:
1. Schema and
A Schema describes the shape of your data graph. It defines a set of types with fields that are populated from your back-end data stores. It is quite simple. It states that the application has 3 types i.e..,
Author, Post, and Query.
A Resolver is a collection of functions that helps generating a response from a GraphQL query. It handles the request and returns a response.
Getting started to Build the project structure in Graphql(Node.JS) these are commands to follow:
First, create a folder, then start our project.
⦁ npm init
Then install some dependencies for our project.
⦁ npm install — save express body-parser
⦁ npm install — save-dev nodemon
Graphql package can be used for the middleware nodejs application and allows to point the schema and resolvers and route request
⦁ npm install — save express-graphql graphql
To connect the server with the MongoDB
⦁ npm install — save mongoose
Structure of the Project as follows:
As we observe in the above figure, the graphql folder contains ‘Schema’ and ‘resolvers’ of the API.
Next, we have a ‘models’ folder that holds what an article should look like, and last but not least, a ‘nodemon.json’ file to hold our environment variables and the entry point of the server ‘app.js’.
With that, we can now add a start script on the ‘package.json’ file to be able as you might guess start the server.
The use of nodemon to start the server and while a file is added or updated nodemon will react to updated automatically.
Next, we have to add the following code block to create a GraphQL schema as
To create a schema, we first have to import build schema from graphql, and next create our types. Here, we have the type Article which must have an _id of type ID, a title, a body, and a createdAt field of type String.
And here to create a new article we use the create article mutation. It receives an object of type ArticleInput and returns the created article.
Now we have everything we need to create a schema, the final thing to do is to pass the Query and the Mutation to the schema.
Now Creating the Mongoose Modules
As I mentioned earlier, MongoDB will be used as a database, and to make things easier, we will use mongoose to interact with it. Now we can create a model for Article.
To create a model of the data, we first import mongoose and access to the schema method.
Now we are creating the folder i.e.., resolvers that we have to add to code as below as
Next, add the code block of the app.js file as show as
The endpoint for all requests will be /graphql, and to be able to reach that endpoint, we need to start the server and listen to port 3000.
Great! we’ve now a working API, but thus far there is still something missing: the API is not connected yet to MongoDB. So, let’s fix that in the next section.
Connect to Mongo DB:
It’s time to connect the API to MongoDB. Next, we use again mongoose and pass as parameters URL and some options to the connect() method. And when the operation is successfully finished, we start the server, otherwise, an error will be thrown.
Test the API with Graphql
To access the GraphQL playground, we have to start the server with the following command:
⦁ npm start
If your browser to http://localhost:8000/graphql you will be able to play with GraphiQL. Create a one new Article
To create the article, we need to send the query mutations.
The mutation creates a new article and returns it as expected. Now, let’s try fetching the articles stored on MongoDB.