DEV Community

Romulo Gatto
Romulo Gatto

Posted on

Using GraphQL with Node.js (e.g., Apollo Server)

Using GraphQL with Node.js (e.g., Apollo Server)

GraphQL is a powerful query language for APIs that was developed by Facebook. It provides a more efficient and flexible way to retrieve data compared to traditional RESTful APIs. In this guide, we will explore how to use GraphQL with Node.js, specifically focusing on the popular library called Apollo Server.

Prerequisites

Before diving into the details of using GraphQL with Node.js, make sure you have the following prerequisites installed:

Setting up a new project

To begin using GraphQL with Node.js, start by setting up a new project:

  1. Create a new directory for your project and navigate into it:
$ mkdir my-project
$ cd my-project
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new npm package in your project directory:
$ npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install the required dependencies:
$ npm install apollo-server graphql
Enter fullscreen mode Exit fullscreen mode

Creating an Apollo Server instance

Once you have set up your project and installed the necessary dependencies, it's time to create an instance of Apollo Server:

  1. Open your text editor and create a new file named server.js.

  2. Import the required modules at the top of server.js:

const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema'); // We'll define this later.
const resolvers = require('./resolvers'); // We'll define this later.
Enter fullscreen mode Exit fullscreen mode
  1. Define the configuration options for your server below the imports:
const server = new ApolloServer({
  typeDefs,
  resolvers,
});
Enter fullscreen mode Exit fullscreen mode
  1. Start listening for incoming requests after defining configuration options:
server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Enter fullscreen mode Exit fullscreen mode

Defining GraphQL Schema

To define the schema for your GraphQL API, create a new file named schema.js:

  1. In your preferred text editor, create a new file named schema.js.

  2. Define your schema using the GraphQL SDL syntax in schema.js. Here's an example:

type Query {
  hello: String
}

type Mutation {
  updateHello(message: String!): String
}
Enter fullscreen mode Exit fullscreen mode

Implementing Resolvers

Resolvers are responsible for resolving requests made to different fields in your schema. Create a new file named resolvers.js:

  1. In your text editor, create a new file named resolvers.js.

  2. Implement resolver functions corresponding to each field defined in the schema. Here's an example:

const resolvers = {
  Query: {
    hello: () => 'Hello from Apollo Server!',
  },
  Mutation: {
    updateHello: (_, { message }) => {
      // Perform some logic or database operations here.
      return message;
    },
  },
};

module.exports = resolvers;
Enter fullscreen mode Exit fullscreen mode

Starting the server

With everything set up, it's time to start the Apollo Server:

  1. Open a terminal window and navigate to the root directory of your project.

  2. Run the following command to start the server:

$ node server.js
Enter fullscreen mode Exit fullscreen mode
  1. You should see a log message indicating that the server is ready and listening on a port.

  2. Open any web browser and visit http://localhost:[PORT]/graphql. Replace [PORT] with the actual port number provided by Apollo Server.

Congratulations! You have successfully created an instance of Apollo Server and implemented basic resolvers for your GraphQL schema. You can now start exploring the powerful capabilities of GraphQL with Node.js.

Feel free to check out the official documentation of Apollo Server and GraphQL for more detailed information on advanced topics and best practices. Happy coding!

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay