Create GraphQL API in Expressjs Project Using Apollo Server Express

Nutan
5 min readNov 24, 2020

--

1. Create express project and install required modules

1.1 Prerequisite

· node

· npm

1.2 Create node project

We will call our project gqlapi. Run the following:

F:

cd F:\javascript-projects\express-projects

mkdir gqlapi

cd gqlapi

npm init

1.3 Install express module in the project

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

npm install express — save

1.4 Install nodeman module in the project

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. It is perfect for development. Install it using npm.

npm install nodemon — save

1.5 Install apollo-server-express

Apollo Server is a flexible, community driven, production-ready HTTP GraphQL middleware for Express, Hapi, Koa, and more. This library that helps you connect a GraphQL schema to an HTTP server in Node.

npm install apollo-server-express — save

1.6 Project folders and files

The following should be your project folder structure at this point of time:

1.7 View installed modules

Open file package.json to see installed modules:

1.8 Open project in your favourite editor

I am using Visual Studio Code editor. You can select any of your favourite editors.

1.9 Add nodeman in package.json file inside scripts section

As stated above, nodemon is the utility that will monitor for any changes in your source and automatically restart your server.

"start": "node ./src/index.js","dev": "nodemon ./src/index.js",

2. Create src folder and in that create index.js file

2.1 Create index.js inside src folder

2.2 Write following code in index.js file

Here, we create an instance of ‘express’ and run it on port 4000.

// file: src/index.js

//include express module or package
const express = require('express');
//create instance of express
const app = express();
app.get('/', (req, res) => res.send('Hello World'));app.listen(4000, () => console.log('Listening on port 4000!'));

3. Run the project

Run with the following code and open the page http://localhost:4000/ in browser.

npm run dev

http://localhost:4000/

4. Add GraphQL API to the project

4.1 Add apollo-server-express in index.js

// file: src/index.js

const { ApolloServer, gql } = require('apollo-server-express');

4.2 Create a GraphQL schema in index.js file

A schema defines a collection of types and the relationships between those types. In this example we have object type ‘Query’. Query type defines one field hello and type is ‘String’.

// file: src/index.js

// GraphQL's schema ‘Query’
const typeDefs = gql`
type Query {
hello: String
}
`;

4.3 Create resolver functions for schema

Apollo Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers.

A resolver is a function that’s responsible for populating the data for a single field in your schema. It can populate that data in any way you define, such as by fetching data from a back-end database or a third-party API.

If you don’t define a resolver for a particular field, Apollo Server automatically defines a default resolver for it.

// file: src/index.js

//Create resolver functions for Query schema
const resolvers = {
Query: {
hello: () => 'Hello world!'
}
};

4.4 Create an instance of Apollo Server

It takes schema and resolvers as input parameters.

// file: src/index.js

//Create an instance of Apollo Server
const server = new ApolloServer({ typeDefs, resolvers });

4.5 Apply middleware and declare path of api

// file: src/index.js

//Apply the Apollo GraphQL middleware and set the path to /api
server.applyMiddleware({ app, path: '/api' });

4.6 Create port constant

// file: src/index.js

const port = 4000;

4.7 Change app.listen like below

// file: src/index.js

app.listen({ port }, () =>
console.log(
`Server running at http://localhost:${port}`
)
);

4.8 Your updated src/index.js

At this point, putting all code together, your src/index.js file should look like:

// file: src/index.js

//include express module or package
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const port = 4000;// GraphQL's schema ‘Query’
const typeDefs = gql`
type Query {
hello: String
}
`;
// create resolver functions for Query schema
const resolvers = {
Query: {
hello: () => 'Hello world!'
}
};
//Create instance of express
const app = express();
//Create an instance of Apollo Server
const server = new ApolloServer({ typeDefs, resolvers });
//Apply the Apollo GraphQL middleware and set the path to /api
server.applyMiddleware({ app, path: '/api' });
app.get('/', (req, res) => res.send('Hello World'));app.listen({ port }, () =>
console.log(
`Server running at http://localhost:${port}`
)
);

5. Run the project

5.1 Nodeman will refresh your server, no need to start again.

Type command given below in browser:

http://localhost:4000/api

5.2 Write query in GraghQL playground

query {
hello
}

5.3 Execute query

Click on highlighted play button

5.4 Output will be like below:

{
“data”: {
“hello”: “Hello world!”
}
}

--

--

Nutan

knowledge of Machine Learning, React Native, React, Python, Java, SpringBoot, Django, Flask, Wordpress. Never stop learning because life never stops teaching.