DEV Community

Ayush Vishwakarma
Ayush Vishwakarma

Posted on

Crafting the Ultimate GraphQL Adventure with Express: Power Up Your API Game!

Hey everyone! As a frontend developer, I've been diving into some backend technologies lately—because let's face it, knowing your way around the backend can save you from any sneaky surprises from your backend developers! 😛

After getting a good grasp of the basics in the MERN stack, I stumbled upon GraphQL, and I have to say, I'm pretty blown away by its potential. It's a game-changer, and I thought it would be fun to share my insights with you all. Let's explore the magic of GraphQL with express together!

Introduction

For people who are fairly new to GraphQL, let me give you a fair introduction to this powerful tool.

GraphQL, as the official website puts it, is A query language for your API. If you've been in the industry for a while, you've likely encountered situations where an API response gives you way more data than you actually need. With a traditional REST API, whether you're using all the keys or just a couple, the entire payload is sent to the client—like getting the entire buffet when all you wanted was a snack.😶‍🌫️

This can lead to inefficiencies, especially when you're only interested in specific data points for different parts of your application. GraphQL tackles this challenge head-on, allowing you to request only what you need, no more, no less. It's like having a tailor-made suit instead of one-size-fits-all!

Let's Get Our Hands Dirty

We’ll tackle this in two main steps:

  1. Creating a GraphQL Server with Apollo Client
  2. Connecting GraphQL with Express

By the end, you'll not only have a GraphQL server up and running, but you'll also know how to connect it with Express. So, roll up your sleeves—it's time to turn code into magic!

Creating a GraphQL Server with Apollo Client

Let's get started by setting up our GraphQL server. First, we'll lay the groundwork with some essential tools.

  1. Initialize an Empty npm Folder

Begin by initializing an npm project. This sets up your project directory with a package.json file that will track your dependencies:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This command will create a basic package.json file with all the default settings—kind of like getting the keys to your new coding kingdom.

  1. Install Express, Apollo Server, Dotenv and GraphQL

Next, we'll bring in the core tools: express for our server, Apollo for our GraphQL needs, and GraphQL itself:

npm i express @apollo/server graphql dotenv
Enter fullscreen mode Exit fullscreen mode

With this, you're setting up the foundation of your GraphQL server. Think of it as assembling the ingredients for a gourmet meal—each one is essential for the final dish.

  1. Install nodemon for Hassle-Free Development

To make your development process smoother, we’ll add nodemon as dev dependencies, nodemon will watch your files for changes and automatically restart the server.

npm i -D nodemon
Enter fullscreen mode Exit fullscreen mode

nodemon is like having a trusty sidekick who handles the grunt work, so you can focus on coding.

  1. Create a src Folder and server.js File

Now, let’s set up the structure of our project. Start by creating a src folder, where all your source code will live. Then, create a server.js file inside src—this will be the starting point of our application:

After installing all these dependencies, your package.json file should look something like this:

Package.json

With this setup, you're now ready to start building your GraphQL server. Buckle up—this is where the real adventure begins!

  1. In our server.js file we'll need to import bunch of things as shown below

Server.js

Let’s walk through the key lines in our server.js file:

  • Apollo and Server Setup: We import ApolloServer and startStandaloneServer to get our GraphQL server rolling, while dotenv handles our environment variables like a pro.

  • We initialize an ApolloServer instance, primarily requiring typeDefs to define the schema. In the provided example, we specify a Query type named check, which is of type String and marked as non-nullable, ensuring that the query will always return a valid string.

  • In addition to typeDefs, the resolvers argument is mandatory. It specifies how to handle and resolve the requested queries. In this case, we’ve defined a resolver for the check query that logs the message checking query and returns a non-nullable string Checking Query, consistent with the schema defined in typeDefs.

  • Finally, we start the server. If all goes well, you’ll see a message in the console confirming that your server is up and running!

Now when you start the server, you'll be able to see a screen similar to the one shown below

Apollo Server Image

Connecting GraphQL with Express

Now that we’ve got our Apollo Server for GraphQL up and running, let’s integrate it with a REST API using Express. It’s a simple tweak, and you’ll be up and running in no time. Follow these steps to make the switch:

  • First, we need to bring in express from express and the expressMiddleware from Apollo Server. This will allow us to blend the best of both REST and GraphQL worlds.

  • Next, we’ll create an instance of an Express app. This will serve as the backbone for our server, handling both REST routes and our GraphQL endpoint.

  • We’ll call the start method from the ApolloServer instance. This prepares the server to handle incoming requests when connected to Express.

  • Finally, we’ll create a /graphql endpoint where our Apollo Server will handle requests using expressMiddleware. This is where the magic happens—combining the flexibility of GraphQL with the simplicity of Express.

Here’s what your updated server.js will look like after making these changes:

Final Server.js

And just like that, when you navigate to http://localhost:8002/graphql, you’ll be greeted by the familiar Apollo Server interface, ready to handle your queries.

Congratulations! You’ve successfully set up a GraphQL server and integrated it with Express. It’s a powerful combo that’s now at your fingertips.

Feel free to share your thoughts in the comments—I’d love to hear how this worked for you. I hope you found this guide helpful, and maybe even a little fun!

Top comments (0)