How to Build A GraphQL API with Node.js, Apollo-Server, and MongoDB Atlas
re you a developer looking to create an efficient and flexible API? Then look no further than GraphQL! GraphQL is a modern way of creating APIs that allow the frontend to request only the data they need, making it a more efficient alternative to REST APIs.
Blog post by Martina Coasel - Published At 4/2/2023
Introduction
Are you a developer looking to create an efficient and flexible API? Then look no further than GraphQL! GraphQL is a modern way of creating APIs that allow the frontend to request only the data they need, making it a more efficient alternative to REST APIs.
If you're a Node.js developer looking to build a GraphQL API, you're in the right place! In this article, you are going to create a food recipe GraphQL API with Node.js, Apollo Server, and MongoDB Atlas. With Apollo Server, you'll get a production-ready GraphQL implementation with many features. MongoDB Atlas is a database service that makes it easy to scale your application.
But before diving into the details, let's ensure we're all on the same page. If you're new to GraphQL, don't worry! You can check out our previous article on the fundamentals of GraphQL . It's an excellent introduction to the topic and a solid foundation for building your GraphQL API.
Prerequisites
- Basic understanding of Node.js syntax and JavaScript
- Fundamentals of GraphQL and its syntax
- npm installed on your computer. You can get it here if you don’t have npm installed on your computer.
Setting up a MongoDB Atlas cluster
Before building the API, you need to set up your MongoDB Atlas cluster. An Atlas cluster is a group of servers configured to store and manage data in MongoDB. These clusters can be customized to meet specific performance, scalability, and security requirements. It’s a straightforward process, and I am going to walk you through the steps.
MongoDB Atlas is a cloud-based database service offered by MongoDB that provides a fully managed and scalable environment for our MongoDB databases. Think of it as a group of computers working together to store and manage data, ensuring it is always available and secure.
To get started,
- Go to the MongoDB Atlas website on your browser by clicking here. If you have an account, you can log in or create one if you are not an existing user. It is free.
- Once signed in, you are going to be redirected to your dashboard, where all the different functionalities and integrations can be performed. Click the “Build a Database” button to start building the database.
- You need to set up basic configurations for your database. Select the M0 Free tier, as it suits your needs.
- Choose any cloud service provider options in the “Provider” section. For this article, I recommend you select the AWS option.
- For the region field, select the region closest to where you are.
- Choose a suitable name for the cluster. It can be simple, as you can't change the name once the cluster is created. You can call your cluster “Food-Recipe” because you are building a food recipe API.
- Once you have configured all primary fields in the template, click the “Create” button. This button creates the Atlas cluster needed for this article.
- It would be best if you also authenticated your connection. MongoDB automatically generates a username and password for the first database user using the details provided during sign-up. To create other users with permission to read and write, choose the “Username and Password” option, which lets you create a user with a username and a secure password. Once you have inputted all the details, click the “Create User” button to save the user credentials.
- You need to enable the network(s) access to read and write data to your cluster. MongoDB automatically adds your current IP address, but you can add more networks to access your cluster. Select the “My Local Environment” option to add an IP address to your network list. Input the IP address and add a short description to identify the IP address. Click the “Add Entry” button to add the network.
- Click the “Finish” button to fully set up the “Food-Recipe” cluster. You can now connect your database to your application and start writing your API.
Connecting your application to the MongoDB database
To connect your application to your MongoDB database. You need to obtain the connection string for your cluster. To obtain the connection string,
- Login to your dashboard, click the “Connect” button for your cluster
- A list of different options to connect your application is available for you to choose from. I recommend you choose the “Drivers” method, as this method lets you use Node.js as your runtime environment.
- Make sure you select the latest version of Node.js. You can then copy the connection string to use in your application. Keep this copy in your notepad, as it is needed in your index.js file to connect your application to your MongoDB database.
Setting up a development environment
In this section, you are going to set up a development environment by creating a project, installing necessary dependencies, and connecting your MongoDB Atlas cluster to your application.
- In your preferred code editor, Open a new terminal and run the following command.COPYCOPYCOPYCOPYnpm init –yes This command creates an empty package.json . The empty package.json is essential for installing and managing the dependencies for the project.
- Installing the dependencies: In the terminal, run the following command.COPYCOPYCOPYCOPYnpm install apollo-server graphql mongoose nodemon The following command installs the four packages needed for this project. The apollo-server dependency lets you create a server that can handle GraphQL queries and mutations. The graphql package provides the tools necessary to build and execute GraphQL queries and mutations, the mongoose package offers a simple way to interact with MongoDB databases, and the nodemon package automatically restarts your Node.js application whenever you make changes to your code.
- Inside your package.json file, you need to include a start command. Whenever you run npm start in the terminal, the start command runs the index.js file, which serves as a server.COPYCOPYCOPYCOPY"scripts": { //Include the start command after the “test” command "start": "nodemon index.js" },
- In your project folder, create an index.js file. The code in the index.js file sets up an Apollo Server that handles your GraphQL queries, and mutations connect to a MongoDB database using mongoose and start listening for requests on a specified port.
- In the index.js file, copy the following code.
COPYCOPYCOPYCOPY// This is getting the ApolloServer object out of the Apollo-server library const { ApolloServer } = require("apollo-server"); // This gives you access to Mongoose from the Mongoose package. const mongoose = require("mongoose"); //You need to create a variable to store the MongoDB string you got from your database. Go to where you saved it and get the string. Replace the `username` and `password` with your MongoDB Atlas username and password. const MONGODB = "mongodb+srv://<username>:<password>@food-recipe.7brtcty.mongodb.net/?retryWrites=true&w=majority" const typeDefs = require("./graphql/typeDefs"); const resolvers = require("./graphql/resolvers"); const server = new ApolloServer({ typeDefs, resolvers, }); //You want your apollo-server to interact with Mongoose by passing in your MongoDB URI mongoose .connect(MONGODB, { useNewUrlParser: true }) .then( // to show when the connection is made () => { console.log("MongoDB Connected Successfully"); return server.listen({ port: 5000 }); } ) // to handle the response object and show where your server is running .then((res) => { console.log(`Server is running on port ${res.url}`); });
Let’s take a closer look at the code, line by line:
COPYCOPYCOPYCOPYconst { ApolloServer } = require("apollo-server");
Here, you're importing the ApolloServer object from the apollo-server library. The object lets you create an Apollo server that can handle GraphQL queries and mutations.
COPYCOPYCOPYCOPYconst mongoose = require("mongoose");
Next, you're importing the mongoose library, a MongoDB library. It provides a simple way to interact with the MongoDB database.
COPYCOPYCOPYCOPYconst MONGODB = "mongodb+srv://feyijimierinle:Backspace@2023@food-recipe.7brtcty.mongodb.net/?retryWrites=true&w=majority";
Here, you defined a variable called MONGODB that stores the URI to your MongoDB database. The URI is a long string that contains your username, password, and host information needed to connect to your database.
COPYCOPYCOPYCOPYconst typeDefs = require("./graphql/typeDefs"); const resolvers = require("./graphql/resolvers");
You're importing the type definitions and resolvers from separate files in a graphql folder. Type definitions describe the structure and functionality of a GraphQL schema. At the same time, resolvers handle the logic for resolving GraphQL queries and mutations.
COPYCOPYCOPYCOPYconst server = new ApolloServer({ typeDefs, resolvers, });
Here, you created an instance of ApolloServer, passing in your type definitions and resolvers as arguments. The instance allows your server to handle GraphQL operations.
COPYCOPYCOPYCOPYmongoose .connect(MONGODB, { useNewUrlParser: true }) .then(() => { console.log("MongoDB Connected Successfully"); return server.listen({ port: 5000 }); }) .then((res) => { console.log(`Server is running on port ${res.url}`); });
Finally, you're connecting to your MongoDB database using the mongoose.connect() method, passing in your MongoDB URI as the first argument. Once the connection is established, you're using the server.listen() to start your Apollo Server, passing in an options object that specifies the port number you want to use (in this case, 5000). Finally, you're logging a message to the console to confirm that the server is running and to indicate where it's listening for requests.
- Go to localhost:5000 on your browser to confirm if your server is running without errors.