How to Build a GraphQL API with Apollo Server and MongoDB

GraphQL provides a flexible alternative to the classic REST approach when you are building APIs.

One of the most important features to consider when designing an application is the type of architecture to use. Effective API design is important in ensuring the application runs smoothly throughout its life.

The RESTful architecture is the most common approach, but it has a significant drawback: an endpoint architecture that returns predefined data. This design can lead to ineffective communication.

In contrast, GraphQL - an alternative to REST - provides more flexibility by allowing you to query only the data you need.

What is GraphQL API?

GraphQL is a query language that you can use to write backend APIs (application programming interfaces). Unlike the REST API, which provides multiple endpoints for different data, the GraphQL API has only one entry point.

Clients can specify the data they need in the query from this single point of entry, making it flexible and efficient in retrieving only the required data.

How to Build a GraphQL API with Apollo Server and MongoDB Picture 1How to Build a GraphQL API with Apollo Server and MongoDB Picture 1

Simply put, the GraphQL API implements the GraphQL architecture described by the GraphQL specifications. This design involves defining schemas, queries, and mutations that the client can interact with.

  1. Schema describes the data types and operations that the API provides. Basically, the schema defines the available data structures and types of queries and tests that the client can run to modify the data.
  2. Query : The client uses queries to fetch data from the database by specifying the structure of the requested data. In addition, clients can nest multiple queries in one HTTP to fetch related data from multiple endpoints.
  3. Mutations are operations used to modify data in the database. The client can send mutation queries to create, update, or delete data.

Set up a MongoDB database

To get started, create a MongoDB database. Then copy the database connection URL string of MongoDB.

Create an Apollo Server

Apollo Server is a popular GraphQL server implementation that allows you to build GraphQL APIs in JavaScript environments, including Node.js, Express, and more.

Create a folder for the new project and the code inside it:

mkdir graphql-API-mongoDB cd graphql-API-mongoDB

Next, initialize a new Node.js project:

npm init --yes

This command creates a file package.json .

Install required dependencies

Run the following command to install the packages.

npm install apollo-server graphql mongoose

Finally, create an index.js file in the project root directory.

Set up Apollo Server

Open index.js and add the code below:

 

const { ApolloServer } = require('apollo-server'); const mongoose = require('mongoose'); const typeDefs = require("./graphql/typeDefs"); const resolvers = require("./graphql/resolvers"); const server = new ApolloServer({     typeDefs,     resolvers }); const MONGO_URI = 'mongodb://localhost:27017'; mongoose   .connect(MONGO_URI, {     useNewUrlParser: true,     useUnifiedTopology: true,   })   .then(() => {     console.log(`Db Connected`);     return server.listen({ port: 5000 });   })   .then((res) => {     console.log(`Server running at ${res.url}`);   })   .catch(err => {     console.log(err.message);   });

This code initializes a local GraphQL server using the Apollo Server library. It then establishes a connection to the MongoDB database using the provided connection URL.

Notice how the code passes two arguments to the new instance of ApolloServer: typeDefs and resolvers. They define the data types and operations the GraphQL API can execute.

After establishing a connection to the MongoDB database, this server starts listening on port 5000.

Define data model

Create a new folder in the root of the project folder and name it models . In this directory, create a new file name dataModel.js and add the following code:

const {model, Schema} = require('mongoose'); const employeeSchema = new Schema({     name: String,     department: String,     salary: String, }); module.exports = model('Employee', employeeSchema);

Define GraphQL Schema

A GraphQL schema defines a data structure that you can query using the GraphQL API. The schema also outlines the queries and mutations that the API can run. You can use queries to fetch data and mutations to edit it.

In the project root, create a new folder and name it graphql. Inside this folder, add 2 files: typeDefs.js and resolvers.js.

Add below code in typeDefs.js file:

const {gql} = require("apollo-server"); const typeDefs = gql`   type Employee {     id: ID!     name: String     department: String     salary: String   }   input EmployeeInput {     name: String     department: String     salary: String   }   type Query {     getEmployee(id: ID): Employee #return Employee by id     employees: [Employee] #return array of Employees   }   type Mutation {     createEmployee(employeeInput: EmployeeInput): Employee     updateEmployee(id: ID, employeeInput: EmployeeInput): Boolean     deleteEmployee(id: ID): Boolean   } `; module.exports = typeDefs;

The above code uses the gql function provided by the apollo-server package to create a GraphQL schema for Employee data.

 

Schema consists of four main elements: data types for employee information, input types, queries, and mutations that the API can implement.

Define Resolvers for GraphQL API

Resolver is a GraphQL function that defines the data to be passed when a client sends an API query to fetch data. Basically, its main role is to extract the requested data from the specific data source and return it to the client.

Add below code to resolvers.js file in graphql folder. In this case, the resolver is specified in the Query and Mutation objects.

The Query object defines two methods: employess and getEmployee. These methods are responsible for fetching employee data from the database as requested by the client.

const Employee= require("./models/employeesModel"); // GraphQL Resolvers const resolvers = {   Query: {     employees: async () => {       try {         const employees = await Employee.find({});         return employees;       } catch (error) {         console.error(error);         throw new Error('Failed to fetch employees');       }     },     getEmployee: async (parent, args) => {       try {         const employee = await Employee.findById(args.id);         return employee;       } catch (error) {         console.error(error);         throw new Error('Failed to fetch employee by ID');       }     },   }, 

The Mutation object has three methods: createEmployee , updateEmployee , and deleteEmployee . They make changes to the data stored in the MongoDB database.

  Mutation: {     async createEmployee (_, { employeeInput: { name, department, salary } }) {       const newEmployee = new Employee({         name: name,         department: department,         salary: salary       });       const response = await newEmployee.save();       console.log(newEmployee);       return {         id: response._id,         .response._doc       }     },     async updateEmployee (_, {id, employeeInput: {name, department, salary}}) {       const updatedEmployee = await Employee.updateOne(         { _id: id },         { name, department, salary }       );       if (!updatedEmployee) {         throw new Error(`Employee with ID: ${id} not found`);       }       return true; // Return a boolean value indicating update success     },     async deleteEmployee (_, {id}) {       const deletedEmployee = await Employee.deleteOne({ _id: id });                if (!deletedEmployee || deletedEmployee.deletedCount === 0) {           throw new Error(`Employee with ID ${id} not found`);       }       return true; // Return a boolean value indicating deletion success     },  }, }; module.exports = resolvers;

Finally, run this command to start the server:

node index.js

After establishing a database connection, this server will start on port 5000.

You can go ahead and test the functionality of the GraphQL API by generating HTTP queries from the GraphQL playground in the browser.

For example, you can use the createEmployee mutation to add new employee data in the MongoDB database .

How to Build a GraphQL API with Apollo Server and MongoDB Picture 2How to Build a GraphQL API with Apollo Server and MongoDB Picture 2

Above is how to build GraphQL API with Apollo Server and MongoDB . Hope the article is useful to you.

4 ★ | 2 Vote