{"id":3272,"date":"2022-08-02T18:43:13","date_gmt":"2022-08-02T23:43:13","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=3272"},"modified":"2022-08-02T18:46:55","modified_gmt":"2022-08-02T23:46:55","slug":"guide-to-build-a-crud-api-with-node-js-and-graphql","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/","title":{"rendered":"Complete Guide To Build a CRUD API With Node.js and GraphQL"},"content":{"rendered":"\n<p>Building a CRUD API lets one know how the communication between the frontend and the backend of the applications works. Using Node.js and GraphQL, you can build a CRUD API that you can connect to virtually any database.\u00a0<\/p>\n\n\n\n<p><strong>Here are the steps to build a CRUD API with Node.js and GraphQL:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Set up a new npm package<\/strong><\/li><li><strong>Install Express and GraphQL<\/strong><\/li><li><strong>Create an index.js file&nbsp;<\/strong><\/li><li><strong>Create a schema.graphql file to define schema<\/strong><\/li><li><strong>Define resolvers in the index.js file<\/strong><\/li><li><strong>Test the CRUD API&nbsp;<\/strong><\/li><\/ol>\n\n\n\n<p>Read on to learn how to build a CRUD API using Node.js and GraphQL!<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#What_is_CRUD\" >What is CRUD?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Steps_to_build_a_CRUD_API_with_Nodejs_and_GraphQL\" >Steps to build a CRUD API with Node.js and GraphQL<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Set_up_a_new_npm_package\" >Set up a new npm package<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Install_Express_and_GraphQL\" >Install Express and GraphQL<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Creating_a_Dummy_Database_Optional\" >Creating a Dummy Database (Optional)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Create_an_indexjs_file\" >Create an index.js file<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Adding_Relevant_Libraries\" >Adding Relevant Libraries<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Creating_GraphQL_webpage_for_query_testing\" >Creating GraphQL webpage for query testing<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Initializing_the_Dummy_Database_Optional\" >Initializing the Dummy Database (Optional)<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Create_a_schemagraphql_File_To_Define_Schema\" >Create a schema.graphql File To Define Schema<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Create_Resolver\" >Create Resolver<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Read_Resolver\" >Read Resolver<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Update_Resolver\" >Update Resolver<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Delete_Resolver\" >Delete Resolver<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Define_Resolvers_in_the_indexjs_file\" >Define Resolvers in the index.js file<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Test_the_CRUD_API\" >Test the CRUD API<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/#Wrapping_Up\" >Wrapping Up<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_CRUD\"><\/span>What is CRUD?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>CRUD is an acronym for Create, Read, Update and Delete. <a href=\"https:\/\/rapidapi.com\/blog\/api-glossary\/crud\/\" target=\"_blank\" rel=\"noopener\">CRUD API<\/a>s provide the basic functionality to manipulate the data in four ways. CRUD is considered a basic cycle. In any given database, it is almost always necessary to have a means of <strong>creating<\/strong> or adding new data, reading the given data stored, updating the data already present, and deleting data that is old or not needed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Steps_to_build_a_CRUD_API_with_Nodejs_and_GraphQL\"><\/span>Steps to build a CRUD API with Node.js and GraphQL<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Set_up_a_new_npm_package\"><\/span>Set up a new npm package<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Before building your API, you will need to create a Node.js project, as, without that, it will not be possible to build your API.<\/p>\n\n\n\n<p>Run the following command to build a new npm package:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>npm init<\/code><\/pre>\n\n\n\n<p>After running the command, keep pressing enter until the command has finished running. This will set everything to default.<\/p>\n\n\n\n<p>The above command creates a new node package for you. In that package, there is a file known as package.json. Without this file, your node.js project can&#8217;t run. The package.json file contains all dependencies and version information etc.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Install_Express_and_GraphQL\"><\/span>Install Express and GraphQL<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>To build a CRUD API, you will need to install Express and GraphQL so you can access the necessary libraries required to build the API.&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/expressjs.com\/\" target=\"_blank\" rel=\"noopener\">Express<\/a> is a Node.js web application framework that backend developers use as it provides multiple features which assist developers in developing mobile and web applications. Simply put, it is a layer on top of the existing Node.js runtime environment which helps manage routes and servers.<\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/graphql.org\/\" target=\"_blank\" rel=\"noopener\">GraphQL<\/a> is a query language used to communicate with databases of different kinds. GraphQL allows you to build APIs which can be evolved and provide the client with access to multiple resources without having to type multiple queries.\u00a0<\/li><\/ul>\n\n\n\n<p>You can use the following command to install Express and GraphQL:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>npm install express  express-graphql  graphql  graphql-tag<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Dummy_Database_Optional\"><\/span>Creating a Dummy Database (Optional)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>For the sake of simplicity, in this article, you will be creating a dummy database using JSON objects. This dummy database will act as an actual database, such as the ones in <a href=\"https:\/\/www.mongodb.com\/nosql-explained\/nosql-vs-sql\" target=\"_blank\" rel=\"noopener\">SQL or MongoDB<\/a>. The reason for not choosing an actual one is to remove the setup complexity and keep focusing on creating an API.<\/p>\n\n\n\n<p>To create a dummy database, go through the following steps:<\/p>\n\n\n\n<p>Run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>npm install notarealdb<\/code><\/pre>\n\n\n\n<p>Create a new folder in your c.urrent directory, and then inside this folder, create a new json file name database.json. Now, create fake data using JSON objects. An example is written below:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>{\n    \"id\": \"1234\",\n    \"name\": \"James\",\n    \"age\": 34\n  },...\n<\/code><\/pre>\n\n\n\n<p>The data provided above is in a JSON object format. Therefore, all your data will be inside an array of JSON Objects, each array member being of type Student. GraphQL itself maps the JSON objects to the schema you provided. Below is the complete data set we will be using for this guide:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>&#91;\n{\n\"id\": \"1234\",\n\"name\": \"James\",\n\"age\": 34\n},\n{\n\"id\": \"1235\",\n\"name\": \"Susan\",\n\"age\" : 28\n\n},\n{\n\"id\": \"1236\",\n\"name\": \"Alex\",\n\"age\": 27\n}\n]\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_an_indexjs_file\"><\/span>Create an index.js file<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>You will need to create an index.js file which will act as your main file in which you will write your queries and resolve all the resolvers present in the schema.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Adding_Relevant_Libraries\"><\/span>Adding Relevant Libraries<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Inside your index.js file, you will need to add libraries. These libraries will allow you to take advantage of the functions to build your API.<\/p>\n\n\n\n<p>Write the following into your index.js file:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/importing relevant libraries\n\nconst express = require('express');              \nconst { graphqlHTTP } = require('express-graphql');\nconst { buildSchema } = require('graphql');\nconst fs = require(\"fs\");\nconst { DataStore } = require('notarealdb');\nconst { report } = require('process');\n\n<\/code><\/pre>\n\n\n\n<p>One thing to note here is how the libraries are imported. The syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const{ &lt;&lt;function name>> } = require ('&lt;&lt;library name>>');<\/code><\/pre>\n\n\n\n<p>The above is used to just import a particular function or a class from the library instead of the entire library.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_GraphQL_webpage_for_query_testing\"><\/span>Creating GraphQL webpage for query testing<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Create an index.js file inside your node package. Inside this file, for now, add the following block of code:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/Creating a GraphQL API Server\n\nconst app = express();\napp.use('\/graphql', graphqlHTTP({\n  schema: schema,\n  rootValue: root,\n  graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at http:\/\/localhost:4000\/graphql');\n<\/code><\/pre>\n\n\n\n<p>The above piece of code allows you to create a GraphQL API server. Through this URL, you can test your queries and mutations and will be able to see the data they are returning.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Initializing_the_Dummy_Database_Optional\"><\/span>Initializing the Dummy Database (Optional)<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>If you have created a dummy database using the module <code>notarealdb<\/code>, you will need to initialize it.<\/p>\n\n\n\n<p>After creating the database file and placing some fake data, you will need to add the following lines to your <code>index.js<\/code> file:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/initialize the database\nconst db = new DataStore('&lt;folder containing database>');\nconst studentDB = db.collection('&lt;filename>');\n<\/code><\/pre>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Note<\/strong>! Make sure to update  <code>'&lt;folder containing database>'<\/code> and <code>'&lt;filename>'<\/code> from the previous snippet of code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_a_schemagraphql_File_To_Define_Schema\"><\/span>Create a <code>schema.graphql<\/code> File To Define Schema<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Now,  create a <code>schema.graphql<\/code> file. This file will contain all the information to define the database and its entities and the queries you will require.<\/p>\n\n\n\n<p>Before getting into how to write the file, it is important to distinguish exactly what you will be requiring. As explained above, CRUD APIs should have the create, read, update and delete functionalities. To add these functionalities, you need to structure the function based on the GrapQL query type.<\/p>\n\n\n\n<p>GraphQL has three major types: Query, Mutation, and Subscription. For this guide, we will be using Query and Mutation.<\/p>\n\n\n\n<p>For all read functions, you will require a resolver of type Query. This will include the read functionality. <\/p>\n\n\n\n<p>Also, you will require a resolver of type Mutation for all the write functions. This will include our Create, Delete, and Update functionalities.<\/p>\n\n\n\n<p>To create a <code>schema.graphql<\/code> file, create a new file with a <code>.graphql<\/code> extension in the same directory as the <code>index.js<\/code> file.<\/p>\n\n\n\n<p>In this file, first, define the entities. In our case, we have only one entity, Student:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>type Student {\n    id: ID!             #! means it cannot be null and is its identifier \n    name: String\n    age: Int\n}\n\n<\/code><\/pre>\n\n\n\n<p>After defining the entity, list all the queries and mutations and the arguments required to execute them successfully. Since we are making a CRUD API, the following are the resolvers and their arguments written in GraphQL:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>type Query {\n    listStudents: &#91;Student]\n    getStudent(id: ID!): Student #Student does not have ! as it can be                                                        return as null\n}\n\ntype Mutation {\n    createStudent(name: String, age: Int): Student!,  \n    deleteStudent(id: ID!): Student,\n    updateStudent(id: ID!, name: String, age: Int): Student\n}\n\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Resolver\"><\/span>Create Resolver<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>In the previous code, the mutation <code>createStudent(name: String, age: Int)<\/code> allows you to add an entry to your database. It returns a Student object to confirm that you have added a student to your database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Read_Resolver\"><\/span>Read Resolver<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>To read data, the code uses two queries <code>getStudent(id: ID!)<\/code> and <code>listStudent[Student]<\/code>. Both of these queries allow you to read the data individually by providing an id or accessing all records respectively.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Update_Resolver\"><\/span>Update Resolver<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>To update data, the code uses the mutation <code>updateStudent(id: ID!, name: String, age: Int)<\/code>. The id is used to identify the entry to be updated, and then the information such as name and age is changed. It then returns the updated student information.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Delete_Resolver\"><\/span>Delete Resolver<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>To delete an entry, the code uses the mutation <code>deleteStudent(id: ID!)<\/code> to find the entry using the id and delete the record associated. The deleted entry is then returned.<\/p>\n\n\n\n<p>After adding every type, your <code>schema.graphql<\/code> file should look something like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>type Query {\n    listStudents: &#91;Student]\n    getStudent(id: ID!): Student       #Student does not have ! as it can be return as null\n}\n\ntype Mutation {\n    createStudent(name: String, age: Int): Student!,       \n    deleteStudent(id: ID!): Student,\n    updateStudent(id: ID!, name: String, age: Int): Student\n}\n\ntype Student {\n    id: ID!                  #! means it cannot be null and it's its identifier \n    name: String\n    age: Int\n}\n\n<\/code><\/pre>\n\n\n\n<p>After creating the schema file, you will need to build a schema for this inside the index.js file. You can use the <code>fs.readFileSync<\/code> function to read the file and use the same function as an argument to the <code><strong>buildSchema<\/strong>()<\/code> method.<\/p>\n\n\n\n<p>One thing to note is that since <code><strong>buildSchema<\/strong>()<\/code> takes a string as an argument, you will need to convert the stream generated when using <code>fs.readFileSync<\/code>  into a string using the <code><strong>toString<\/strong>()<\/code> method.<\/p>\n\n\n\n<p>Add this line to your index.js file:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ Construct a schema, using GraphQL schema language\nvar schema = buildSchema(fs.readFileSync(\"schema.graphql\").toString());<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Define_Resolvers_in_the_indexjs_file\"><\/span>Define Resolvers in the index.js file<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The resolvers that you listed in the <code>schema.graphql<\/code> will have to be defined for them to work as intended. Defining these resolvers can be thought of as writing a query for the particular database the API is connected to.<\/p>\n\n\n\n<p>It&#8217;s important to know that since one query or mutation maps to exactly one resolver, you should name your resolver and the query or mutation the same. Add the following piece of code to your index.js file:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ root provides a resolver function for each API endpoint or CRUD functionality\nvar root = {\n\nlistStudents: () => {\n    return studentDB.list()\n},\ngetStudent: (argument) => {\n    return studentDB.get(argument.id)\n},\ncreateStudent: (argument) => {\n    const studentStuff = {\n        id: argument.id,\n        name: argument.name,\n        age: argument.age \n    }\n    return studentDB.create(studentStuff);\n},\ndeleteStudent: (argument) => {\n    const studentObj = studentDB.get(argument.id);\n    studentDB.delete(argument.id);\n    \n    return studentObj;\n},\nupdateStudent: (argument) => {\n    const studentStuff = {\n        id: argument.id,\n        name: argument.name,\n        age: argument.age \n    }\n    studentDB.update(studentStuff);\n    const studentObj = studentDB.get(argument.id);\n    \n    return studentObj;\n}\n};\n<\/code><\/pre>\n\n\n\n<p>The <code>root<\/code> variable acts as a defining function for all the CRUD functionalities or API endpoints. Inside root, you can define each endpoint and consider them as methods. For example, suppose <code>deleteStudent()<\/code> is called. In that case, the code written inside the root for <code>deleteStudent()<\/code> will be executed, which will then make changes to your database as defined by the schema.<\/p>\n\n\n\n<p>Since we are using a dummy database, it is important to specify that all the code written above inside <code>root<\/code> is only pertinent to the dummy database. Write queries inside <code>root<\/code> for databases made with SQL, MongoDB, or any other query language.<\/p>\n\n\n\n<p>After adding all the code explained above, your index.js file should look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/importing relevant libraries\n\nconst express = require('express');              \nconst { graphqlHTTP } = require('express-graphql');\nconst { buildSchema } = require('graphql');\nconst fs = require(\"fs\");\nconst { DataStore } = require('notarealdb');\nconst { report } = require('process');\n\n\/\/initialize the database\nconst db = new DataStore('database');\nconst studentDB = db.collection('studentData');\n\n\/\/ Construct a schema, using GraphQL schema language\nconst schema = buildSchema(fs.readFileSync(\"schema.graphql\").toString());  \/\/returns a buffer but buildschema needs string so we convert to string\n\n\n\/\/ root provides a resolver function for each API endpoint or CRUD functionality\nconst root = {\nlistStudents: () => {\n    return studentDB.list()\n},\ngetStudent: (argument) => {\n    return studentDB.get(argument.id)\n},\ncreateStudent: (argument) => {\n    const studentStuff = {\n        id: argument.id,\n        name: argument.name,\n        age: argument.age \n    }\n    return studentDB.create(studentStuff);  \n},\ndeleteStudent: (argument) => {\n    const studentObj = studentDB.get(argument.id);\n    studentDB.delete(argument.id);\n    \n    return studentObj;  \n},\nupdateStudent: (argument) => {\n    const studentStuff = {\n        id: argument.id,\n        name: argument.name,\n        age: argument.age \n    }\n    studentDB.update(studentStuff);\n    const studentObj = studentDB.get(argument.id);\n    \n    return studentObj;\n}\n};\n\n\/\/Creating a GraphQL API Server\n\nconst app = express();\napp.use('\/graphql', graphqlHTTP({\n  schema: schema,\n  rootValue: root,\n  graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at http:\/\/localhost:4000\/graphql');<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Test_the_CRUD_API\"><\/span>Test the CRUD API<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now, your API should be ready for testing!<\/p>\n\n\n\n<p>To test your API, first, run your Node.js application by running the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>node index.js<\/code><\/pre>\n\n\n\n<p>After running the above command, you will see a localhost URL in the terminal, which will take you to a GraphiQL page. The GraphiQL page allows you to run your queries and mutations. You will see live changes to your data by opening the database.js file you created (if you created a dummy database) or by checking the database you connected.\u00a0<\/p>\n\n\n\n<p>It is important to note that you can only run a single query or a single mutation at a time on the GraphiQL page.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Wrapping_Up\"><\/span>Wrapping Up<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Congratulations! You created a CRUD API using Node.js and GraphQL. You learned how to create and define resolvers. You also learned how to create a dummy database, allowing you to practice your skills before using a real database.<\/p>\n\n\n\n<p><strong>Was this post helpful? <\/strong><\/p>\n\n\n\n<p>Please, let us know your opinions by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter of Become A Better Programmer.<\/a><\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">Are you learning web development using <a href=\"https:\/\/twitter.com\/hashtag\/NodeJS?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#NodeJS<\/a>  and <a href=\"https:\/\/twitter.com\/hashtag\/GraphQL?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#GraphQL<\/a>  and don&#39;t know where to start?<br><br>No worries, we got you covered with this guide to build a CRUD API with Node.js and GraphQL.<a href=\"https:\/\/t.co\/fkgZKoOv2D\">https:\/\/t.co\/fkgZKoOv2D<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1554614656798441473?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">August 2, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Building a CRUD API lets one know how the communication between the frontend and the backend of the applications works. Using Node.js and GraphQL, you can build a CRUD API that you can connect to virtually any database.\u00a0 Here are the steps to build a CRUD API with Node.js and GraphQL: Set up a new &#8230; <a title=\"Complete Guide To Build a CRUD API With Node.js and GraphQL\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/guide-to-build-a-crud-api-with-node-js-and-graphql\/\" aria-label=\"More on Complete Guide To Build a CRUD API With Node.js and GraphQL\">Read more<\/a><\/p>\n","protected":false},"author":6,"featured_media":3391,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[23],"tags":[],"class_list":["post-3272","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3272","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=3272"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3272\/revisions"}],"predecessor-version":[{"id":3392,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3272\/revisions\/3392"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3391"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=3272"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=3272"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=3272"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}