GraphQL has become a popular alternative to REST for building APIs, thanks to its flexibility and efficiency. In this blog post, I will guide you through creating a GraphQL API using Node.js and Apollo Server. We’ll cover the basics, set up a sample project, and implement a few features that demonstrate the power of GraphQL.
What is GraphQL?
GraphQL is a query language for APIs, developed by Facebook, that allows clients to request only the data they need. Unlike REST, where you might have multiple endpoints for different data, GraphQL exposes a single endpoint and lets you define the structure of the response.
Setting Up Your Node.js Environment
To get started, ensure you have Node.js installed on your machine. You can check this by running:
node -v
Once you have Node.js set up, create a new directory for your project and initialize a new Node.js application:
mkdir graphql-api-example
cd graphql-api-example
npm init -y
Next, we need to install Apollo Server and GraphQL:
npm install apollo-server graphql
Creating a Simple GraphQL Server
Let’s create a basic GraphQL server. In your project directory, create a file named index.js and add the following code:
const { ApolloServer, gql } = require('apollo-server');
// Sample data
const books = [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' },
];
// Type definitions
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
// Resolvers
const resolvers = {
Query: {
books: () => books,
},
};
// Apollo Server setup
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
This code sets up an Apollo Server with a simple schema that defines a Book type and a query books that returns a list of books. The server listens for incoming requests and logs the URL to the console.
Querying Your GraphQL API
Once your server is running, you can test it using GraphQL Playground, which is included with Apollo Server. Open your browser and navigate to the URL logged in the console (usually http://localhost:4000/). You can execute the following query:
query {
books {
title
author
}
}
This query will return a list of books along with their authors. The response will look something like this:
{
"data": {
"books": [
{ "title": "The Awakening", "author": "Kate Chopin" },
{ "title": "City of Glass", "author": "Paul Auster" }
]
}
}
GraphQL allows you to specify exactly the data you want, making your API more efficient.
Implementing Mutations
In addition to querying data, GraphQL allows you to modify it through mutations. Let’s enhance our server by adding a mutation to add a new book. Update your typeDefs and resolvers as follows:
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String, author: String): Book
}
`;
const resolvers = {
Query: {
books: () => books,
},
Mutation: {
addBook: (parent, { title, author }) => {
const newBook = { title, author };
books.push(newBook);
return newBook;
},
},
};
With this mutation, we can now add books to our list. To test it, run the following mutation in GraphQL Playground:
mutation {
addBook(title: "1984", author: "George Orwell") {
title
author
}
}
This will return the newly added book, and you can then query the books query again to see the updated list.
Key Takeaways
- GraphQL provides a flexible and efficient way to interact with APIs.
- Apollo Server makes it easy to set up a GraphQL server in Node.js.
- GraphQL allows clients to request exactly the data they need.
- Mutations enable you to modify data within your API.
In this post, we explored the basics of building a GraphQL API using Node.js and Apollo Server. By leveraging the capabilities of GraphQL, you can create responsive and efficient APIs that meet the needs of modern applications.