In this guide, we will build from scratch an API with GraphQL, Node JS, Express, and MongoDB. So, let’s start by answering an important question: what is GraphQL?
If you’re interested in learning Node JS, Express and GraphQL in a comprehensive way, I highly recommend this bestseller course: NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)
It’s an affiliate link, so by purchasing, you support the blog at the same time.
GraphQL is a query language created by Facebook. It’s an alternative to the REST approach. So, if you come from the REST world, just keep in mind that GraphQL works differently. It has one single endpoint for all kinds of requests, and the method has to be a post request. GraphQL works with types and fields, and it’s really powerful since it provides all or just the needed data.
Send a GraphQL query to your API and get exactly what you need, nothing more and nothing less.
We will see it in action later, but for now, let’s plan our API.
For the API, we will have the possibility to create articles and store them in MongoDB. And also be able to fetch them back.
To do so, we have to create a new project by running the following command in the terminal.
yarn init
In this tutorial, I will use yarn
, you can use npm
if you want too. It’s really up to you
Next, structure your project as follow:
├── node_modules
├── graphql
| ├── resolvers
| | └── index.js
| └── schema
| └── index.js
├── models
| └── article.js
├── app.js
├── nodemon.json
├── package.json
└── yarn.lock
As you can see, we have a graphql
folder that keeps the schema and the resolvers of the API.
Next, we have a models
folder which holds what an article should looks like and last but not the least, a nodemon.json
file to hold our environment variables and the entry point of the server app.js
.
We have a couple of libraries to install, so I will keep things simple and install the needed one as we progress.
Now, let’s run the following commands on the terminal to install express
and nodemon
.
yarn add express
Next, add nodemon
as a development dependency.
yarn add nodemon -D
With that, we can now add a start script on the package.json
file to be able as you might guess start the server.
#mongodb #node js #express