Building Modern APIs: How to Use GraphQL with Node.js
GraphQL gives you a powerful way to query your data, and Node.js makes it easy to build a server. In this tutorial, you’ll set up a simple GraphQL API with Node.js using express-graphql and graphql libraries.
1. Set Up the Project
Initialize a Node project and install the core dependencies:
npm init -ynpm install express express-graphql graphql
Create an index.js file and import the required modules.
2. Define Your Schema
GraphQL requires a schema that describes the data types and available queries. For example, a simple Book type:
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type Book {
id: ID!
title: String
author: String
}
type Query {
books: [Book]
}
`);
3. Create Resolvers
Resolvers tell GraphQL how to fetch data. Here’s a sample resolver that returns an array of books:
const root = {
books: () => {
return [
{ id: 1, title: '1984', author: 'George Orwell' },
{ id: 2, title: 'Brave New World', author: 'Aldous Huxley' }
];
}
};
4. Wire It All Together
Attach the GraphQL middleware to an Express server:
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
rootValue: root,
graphiql: true
}));
app.listen(4000, () => console.log('Server running on port 4000'));
Now run node index.js and open http://localhost:4000/graphql to test queries in the GraphiQL IDE.
Conclusion
You’ve built a functional GraphQL API with Node.js in just a few steps. From here, you can expand the schema, add mutations, and connect a database. GraphQL gives you flexibility and efficiency—start using it today.