Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. GraphQL, on the other hand, is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. Combining these two technologies allows developers to create powerful and efficient APIs.
In this tutorial, we will explore how to integrate GraphQL into an Express.js application. We'll cover the basics of setting up a GraphQL server, defining types, resolvers, and handling queries and mutations. By the end of this guide, you should have a solid understanding of how to use GraphQL with Express.js to build robust APIs.
GraphQL is a query language for APIs that provides a more efficient, powerful, and flexible alternative to REST. It allows clients to request exactly what they need and nothing more, reducing over-fetching and under-fetching issues common in RESTful APIs.
First, let's set up a basic Express application and integrate GraphQL into it.
Open your terminal and create a new directory for your project. Navigate into the directory and initialize a new Node.js project:
$ mkdir graphql-express-app$ cd graphql-express-app$ npm init -y
Install Express, Apollo Server (a popular GraphQL server library), and GraphQL itself:
You should see output indicating that the server is running:
🚀 Server ready at http://localhost:4000/graphql
Open your browser and navigate to http://localhost:4000/graphql. You will see the Apollo GraphQL Playground, where you can test your queries. Try running the following query:
1{2hello3}
You should receive a response like this:
{
"data": {
"hello": "Hello world!"
}
}Let's extend our GraphQL server to handle more complex queries and mutations.
Update your index.js file to include a more complex schema with types, queries, and mutations.
1const express = require('express');2const { ApolloServer, gql } = require('apollo-server-express');34// Define your GraphQL schema5const typeDefs = gql`6type User {7id: ID!8name: String!9email: String!10}1112type Query {13users: [User]14user(id: ID!): User15}1617type Mutation {18addUser(name: String!, email: String!): User19}20`;2122// Define resolvers for your schema23const users = [24{ id: '1', name: 'Alice', email: 'alice@example.com' },25{ id: '2', name: 'Bob', email: 'bob@example.com' },26];2728const resolvers = {29Query: {30users: () => users,31user: (_, { id }) => users.find(user => user.id === id),32},33Mutation: {34addUser: (_, { name, email }) => {35const newUser = { id: String(users.length + 1), name, email };36users.push(newUser);37return newUser;38},39},40};4142// Create an Apollo Server instance43const server = new ApolloServer({ typeDefs, resolvers });4445// Initialize an Express application46const app = express();4748// Apply the Apollo GraphQL middleware to the Express application49server.applyMiddleware({ app });5051// Start the server on port 400052app.listen({ port: 4000 }, () =>53console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)54);
Restart your server if it's running, then open the Apollo GraphQL Playground again. Try running the following queries and mutations:
Query for all users:
1{2users {3id4name56}7}
Query for a specific user by ID:
1{2user(id: "1") {3id4name56}7}
Add a new user:
1mutation {2addUser(name: "Charlie", email: "charlie@example.com") {3id4name56}7}
You should see the expected responses for each query and mutation.
Now that you have a basic understanding of integrating GraphQL with Express.js, you can explore more advanced features such as:
For further learning, consider checking out the Apollo Server documentation and exploring more advanced use cases of GraphQL with Express.js. Additionally, you might want to dive into building microservices architectures using Express.js, which we will cover in future tutorials.