GraphQL is a powerful query language for APIs that has gained a lot of popularity in recent years. With its ability to handle complex data queries and provide efficient data retrieval, it has become a go-to technology for many developers. In this article, we will explore how to build GraphQL APIs with Node.js, a popular server-side JavaScript framework.
Before diving into the details, let's briefly understand what GraphQL is and why it is so popular. GraphQL is a query language for APIs that was developed by Facebook in 2012. It provides a more efficient, powerful, and flexible alternative to traditional REST APIs. With GraphQL, clients can request only the data they need, which reduces over-fetching and under-fetching of data.
To get started with building GraphQL APIs with Node.js, we will need to install some dependencies. Firstly, we need to install Node.js, which comes with the npm package manager. Next, we need to install the Apollo Server, a popular GraphQL server implementation for Node.js. We can do this by running the following command in our terminal:
npm install apollo-server graphql
Once we have installed these dependencies, we can start building our GraphQL API. The first step is to define our data model, which is the schema. The schema defines the types of data we will be working with and the operations we can perform on that data. We will create a schema using the GraphQL schema definition language (SDL). Here's an example schema:
type Book {
id: ID!
title: String!
author: String!
}
type Query {
books: [Book!]!
book(id: ID!): Book!
}
type Mutation {
createBook(title: String!, author: String!): Book!
}
In this schema, we define two types: Book
and Query
. The Book
type has three fields: id
, title
, and author
. The Query
type defines two operations: books
, which returns an array of books, and book
, which takes an id
parameter and returns a single book. We also define a Mutation
type that allows us to create a new book.
Now that we have defined our schema, we need to implement it using the Apollo Server. We can create an instance of the server and pass our schema to it like this:
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const books = [
{
id: '1',
title: 'Harry Potter and the Philosopher\'s Stone',
author: 'J.K. Rowling',
},
{
id: '2',
title: 'The Hobbit',
author: 'J.R.R. Tolkien',
},
];
const resolvers = {
Query: {
books: () => books,
book: (parent, { id }) => books.find((book) => book.id === id),
},
Mutation: {
createBook: (parent, { title, author }) => {
const newBook = {
id: String(books.length + 1),
title,
author,
};
books.push(newBook);
return newBook;
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
In this code, we define our resolvers
object, which contains the implementations for the queries and mutations defined in our schema. We also define some initial data for our books
array. Finally, we create an instance of the Apollo Server and pass our schema and resolvers to it.
We can now start our server by running node index.js
in our terminal. Once the server is running, we can open the GraphQL Playground by visiting http://localhost:4000
in our web browser.
In the GraphQL Playground, we can interact with our API by running queries and mutations. Here's an example query to retrieve all books:
query {
books {
id
title
author
}
}
And here's an example mutation to create a new book:
mutation {
createBook(title: "The Lord of the Rings", author: "J.R.R. Tolkien") {
id
title
author
}
}
In this article, we have covered the basics of building GraphQL APIs with Node.js. We started by defining our schema using the GraphQL SDL, and then implemented it using the Apollo Server. We also looked at some examples of queries and mutations that we can run against our API.
With GraphQL's flexible and efficient data retrieval, and Node.js' powerful server-side JavaScript capabilities, building GraphQL APIs with Node.js has become a popular choice for many developers. By following the steps outlined in this article, you can get started with building your own GraphQL API in no time!
Thanks for reading...
Happy Coding
Top comments (2)
Wow, thanks for the helpful tips
It should also be mentioned that The Guild has a full suite of completely open-source tools for graphql, including the widely used graphql-code-generator and multiple options for servers including Yoga and Envelop. They also have federation and schema management tools. And they can be built out as leaner servers vs Apollo.