Creating a Backend Project
Learn how to set up a Node.js GraphQL backend with Apollo Server.
We'll cover the following
Creating a Node.js project
Now that we have all the prerequisites, let’s create our project. The final project in the GitHub repo contains the server (with the backend code) and client (with the frontend code) folders. All the commands in this course section are executed in the server folder.
To create a project, we can run the following command:
npm init
It’ll ask us a few questions about how we want to set up our project. Once it’s finished, it will send a package.json
file containing our project’s configuration.
We also need to add two dependencies. One is for Apollo Server, which will allow us to implement the GraphQL API.
npm install apollo-server
The second one is a nodemon
tool that can automatically restart our application if any source files change. The application doesn’t need the nodemon
tool to work, but it’s easier to develop with this option.
npm install --save-dev nodemon
All the code will initially be placed in the src/index.js
file, which is empty right now.
As a result of all these commands, the directory structure will look like this:
├── package-lock.json
├── package.json
└── src
├── index.js
At this stage, our package.json should look like this:
{"name": "products-server","version": "1.0.0","description": "","main": "src/index.js","scripts": {"start": "nodemon src/index.js"},"author": "Ivan Mushketyk","dependencies": {"apollo-server": "^3.0.2"},"devDependencies": {"nodemon": "^2.0.12"}}
The only thing that we need to add manually is the start script, which will allow us to run our application.
"scripts": {"start": "nodemon src/index.js"}
This code will allow us to run the npm start
command to start our backend. That will, in turn, run the nodemon
command that’ll run the src/index.js
, which is an entry point for our backend server.
Implementing the first GraphQL query
Once we have the project’s structure, we can start writing the first GraphQL query. Our first query will be simple and return a static string with the application’s name.
Here’s the GraphQL schema that we’ll implement:
type Query {appName: String}
Now, let’s start working on the content of the index.js
file and implement a simple GraphQL server that implements this single query.
To get our GraphQL server up and running, we first need to create an instance of an ApolloServer
class from the apollo-server
library. To do this, we need to provide two parameters. First, a schema for our API, and then resolvers that implement that schema.
const { ApolloServer, gql } = require('apollo-server')const server = new ApolloServer({typeDefs: typeDefs, // schema for our GraphQL APIresolvers: resolvers, // implementation of queries and types})
First, let’s see how we can define the schema of our API. We can do it in the index.js
source file, which will look like this:
const typeDefs = gql`type Query {appName: String}`
This syntax might seem unusual to you if you’re unfamiliar with modern JavaScript. The string surrounded by the “`” symbols is called a template literal. It allows us to define multiline strings and substitute the results of JavaScript expressions in a string.
The gql
prefix in front of the string is syntax sugar for calling the gql function.
gql(`...`)
While the code might look unusual, it just passes a multiline string to the gql
function. Why do we need to call this function? Because it parses the GraphQL schema that we define. Then we can parse the result to the ApolloServer
constructor.
Now, we need to define how to implement our API. To do this, we need to specify what to do when a user sends a request for the appName
query. This is the purpose of the second parameter for the ApolloServer
constructor, called resolvers
, which in our case is simply a function that processes the appName
query.
For apollo-server
, we need to define it like this:
const resolvers = {Query: {appName: () => 'ProductHunt clone'},}
Here, the object assigned to resolvers
provides an implementation for the whole GraphQL API. This object only has the Query
field, which provides implementations for queries that our API provides. We’ll see how we can provide other fields to this object later.
The only query that it implements is the appName
, which simply returns a static string.
appName: () => 'ProductHunt clone'
If the code above seems a bit confusing, here’s a graphical representation of the relationship between the resolver definition and GraphQL schema.
One last thing that we’ll do is apply a bit of syntax sugar, which is commonly used in JavaScript to shorten an object definition if the name of an object key and the name of a variable assigned to it are the same.
const server = new ApolloServer({typeDefs,resolvers,})
When we combine everything together, the result looks like this:
const typeDefs = gql`type Query {appName: String}`const resolvers = {Query: {appName: () => 'ProductHunt clone'},}const server = new ApolloServer({typeDefs,resolvers,})
The only thing left to do is start the server. To do this, we need to call the server.listen()
method. This method returns an instance of a Promise, representing an asynchronous work item that is not necessarily finished. It’s similar to Future in other languages like Java. If we call then()
on the instance of Promise and pass a function to it, it will be called when our server is ready to process requests.
server.listen().then(() => {console.log('Listening on port 4000')})
Our simple GraphQL server is ready! We can start it by running the npm start
command.
npm start
This calls the command that was defined in the package.json
earlier in this lesson and will run the nodemon src/index.js
command.
$ npm start> products-server@1.0.0 start> nodemon src/index.js[nodemon] 2.0.12[nodemon] to restart at any time, enter `rs`[nodemon] watching path(s): *.*[nodemon] watching extensions: js,graphql[nodemon] starting `node src/index.js`Listening on port 4000
Once we see this output, we can go to this URL to send requests to our GraphQL server: localhost:4000/graphql.
This link has an invitation to use Apollo’s GraphQL explorer.
The explorer is available offline, but once opened, it can send GraphQL requests to our local dev. environment. By default, it’s configured to send requests to localhost:4000
.
Now, it’s time to send the first query to our GraphQL API.
query {appName}
When we run this query, we should get the following result:
{"data": {"appName": "ProductHunt clone"}}
This is how it looks in a browser:
Interactive demo
We can run the current version of our application using the interactive demo after each lesson in the course.
To run the app, click the “Run” button at the bottom of the interactive demo and wait until you see the output shown below appears. It might take a minute or two for the result to show.
Listening on the port 4000
Once the application is running, clicking on the link at the bottom of the code widget will let us use GraphQL Explorer to send GraphQL queries.
{ "ext": "js,graphql", "delay": 2000 }
At this stage, we have scaffolding for our GraphQL server, and we can start building our app. But before we move on, let’s refactor it a bit to make it more maintainable.
Source code
To get the source code for this chapter, we can run the following command in the project’s repository:
git checkout initial-version
Summary
In this lesson, we’ve looked at how to create a simple GraphQL server from scratch and query it using Apollo Studio.