Exploring GraphQL: Implementing Todo APIs with Node.js, MongoDB & GraphQL

Exploring GraphQL: Implementing Todo APIs with Node.js, MongoDB & GraphQL

In today’s dynamic world of web development, where data is king and flexibility is paramount, GraphQL has emerged as a game-changer. As developers, we’re always on the lookout for technologies that streamline our workflows, enhance performance, and empower us to build robust APIs. In this article, we’ll explore GraphQL and implement a todo list using GraphQL with NodeJS.

What is GraphQL?

Imagine having a superpower that allows you to fetch exactly the data you need from your server with a single request. That’s precisely what GraphQL brings to the table. Unlike traditional REST APIs, where you’re often stuck with predefined endpoints that return fixed data structures, GraphQL gives you the freedom to specify the shape of your response on the client side. It’s like having a tailor-made suit for your data fetching needs.

Why GraphQL was Needed?

While REST APIs worked well for many use cases, they had limitations, especially when it came to data fetching. One common problem was over-fetching and under-fetching of data, where clients received more or less data than they actually needed, leading to performance issues and wasted network bandwidth. Additionally, as applications grew in complexity, managing multiple endpoints and versioning became cumbersome with REST.

How GraphQL Fulfilled the Need?

GraphQL emerged as a solution to these challenges by offering a more flexible approach to data retrieval. Instead of fixed endpoints returning predefined data structures, GraphQL allows clients to specify exactly what data they need using a single query. This eliminates over-fetching and under-fetching of data, reduces the number of network requests, and enables clients to fetch data from multiple sources in a single request.

Benefits of GraphQL

  1. Flexible Data Retrieval: Clients can request precisely the data they need, avoiding over-fetching and under-fetching.
  2. Strongly Typed Schema: GraphQL APIs are defined by a schema that serves as a contract between the client and server, providing clear documentation and enabling powerful tooling.
  3. Versionless: GraphQL APIs are versionless, allowing for gradual schema changes without breaking existing clients.
  4. Rapid Development: GraphQL accelerates development by enabling front-end and back-end teams to work autonomously and iterate quickly on features.

Drawbacks of GraphQL

  1. Complexity: GraphQL introduces complexity in managing schemas, resolving queries, and optimizing performance.
  2. Learning Curve: Developers new to GraphQL may face a learning curve in understanding its concepts compared to REST.
  3. Caching Challenges: GraphQL presents challenges in caching responses due to the dynamic nature of queries and lack of standardized caching mechanisms.

Performance Comparison: REST vs GraphQL

GraphQL proves to be more efficient in terms of resource usage, requiring less CPU and memory. However, when it comes to speed and throughput, REST takes the lead. A study found that REST outperforms GraphQL with a faster response time and higher throughput, boasting a 50% improvement in response time and 37% increase in throughput. However, GraphQL has been shown to use fewer resources, reducing CPU utilization by 37% and memory usage by 39%.

Fig 1.1: Performance comparison data between GraphQL and REST

Implementing TODO list with GraphQL

Before diving into the implementation, let’s cover some basics of GraphQL.

  • Schema: GraphQL APIs are defined by a schema that describes the capabilities of the API. It defines types of data that can be queried and the relationships between those types.
  • Queries: Queries in GraphQL are used to request specific data from the server. They resemble the shape of the data that you expect back.
  • Mutations: Mutations are operations that modify data on the server. They are used for creating, updating, or deleting data.
  • Resolvers: Resolvers are functions that resolve the fields in a query or mutation and return the data.

We’ll use the following folder structure for our implementation:

Step-0: Install dependencies

npm init --y
npm install apollo-server-express express graphql mongoose

The apollo-server-express package is an integration of Apollo Server with Express, allowing you to easily set up a GraphQL server within your Express application. It provides a simple and efficient way to define your GraphQL schema, resolvers, and other server configurations. This package is essential for building GraphQL APIs with Node.js and Express.

Step-1: Define mongodb schema

In src/models, create todo.js file and define mongodb schema as below:

Step-2: Define Resolvers for Todos

In src/resolvers, create todoResolver.js file and define this resolver as below:

Step-3: Define GraphQL schema

In GraphQL, a schema defines the structure of the data that can be queried or mutated. It specifies the types of data available and the operations that can be performed on them.

Step-4: Set Up Server, MongoDB Connection, and GraphQL Integration

In this step, we configure the server, establish a connection to MongoDB, and integrate GraphQL into our Node.js application. The code snippet initialises an Express server, sets up Apollo Server for GraphQL, establishes a connection to the MongoDB database, and starts the server to listen for incoming requests. 

Great! Everything is set up now. Let’s run the application by executing the following command in your terminal:

node src/app.js

Once the server starts, you’ll see the following message in your terminal:

Server running on http://localhost:3000/graphql

Now, open your web browser and navigate to the URL http://localhost:3000/graphql. You'll be greeted with a beautiful GraphQL Apollo UI, allowing you to interact with the API effortlessly.

Step-5: Let’s test the app

After visiting http://localhost:3000/graphql, you’ll be able to write queries. Let’s start by running a mutation to create a new todo:

Creating Todo in Apollo GraphQL Explorer

Hit the run button, and the task will be created in the local database. You can verify this by checking your MongoDB database.

Local MongoDB

Now, let’s see the real magic of GraphQL by running a query to fetch data from the application. Even though there are multiple fields in the todo document, let’s say we only want the task ID and title in the response. This is where GraphQL shines — we can fetch data from the database as per our specific requirements.

Querying Todo in Apollo GraphQL Explorer

Wrapping Up

In today’s world, GraphQL has become popular for building APIs because it fetches data precisely as needed. We implemented a todo list app in Node.js using GraphQL. GraphQL is advantageous because it fetches only the data you request, unlike REST APIs, which often send too much or too little data. It’s like ordering a custom-made meal instead of a set menu. However, GraphQL can be tricky to learn, and caching data with it is a bit challenging. Generally, we found that REST is faster but uses more resources, while GraphQL is more efficient with resources but slightly slower. By following our guide, you can use GraphQL to build APIs that suit your needs and deliver a great user experience.