# GraphQL API Development with Node.js and Apollo Server
GraphQL has revolutionized the way APIs are developed and consumed. Unlike REST APIs, GraphQL provides a flexible and efficient way to query data, allowing clients to request exactly what they need. In this tutorial, we’ll explore how to develop a GraphQL API using Node.js and Apollo Server.
—
## What is GraphQL?
GraphQL, developed by Facebook, is a query language for APIs that offers a powerful runtime for executing queries on your data. Its key features include:
1. **Declarative Data Fetching**: Clients specify the shape and structure of the data they need.
2. **Single Endpoint**: Instead of multiple endpoints, GraphQL APIs expose a single endpoint.
3. **Flexible and Efficient**: Avoid over-fetching or under-fetching data.
—
## Why Apollo Server?
Apollo Server is one of the most popular GraphQL server implementations. It integrates seamlessly with Node.js and provides features like middleware support, subscriptions, schema stitching, and more.
—
## Setting Up the Project
To get started, follow these steps:
### 1. Initialize a Node.js Project
Create a new directory for your project and initialize it with `npm`.
mkdir graphql-api && cd graphql-api
npm init -y
—
### 2. Install Dependencies
Install Apollo Server, GraphQL, and other required packages.
npm install apollo-server graphql
—
### 3. Create the Server
Let’s write the code for a basic Apollo Server setup.
const { ApolloServer, gql } = require('apollo-server');
// Define your schema using GraphQL SDL
const typeDefs = gql`
type Query {
hello: String
}
`;
// Define resolvers
const resolvers = {
Query: {
hello: () => "Hello, world!"
}
};
// Create an Apollo Server instance
const server = new ApolloServer({ typeDefs, resolvers });
// Start the server
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
—
## Explaining the Code
1. **Schema Definition**: The `typeDefs` variable contains GraphQL schema definitions using the Schema Definition Language (SDL). Here, we define a `Query` type with a single `hello` field.
2. **Resolvers**: Resolvers map queries to their corresponding functions. In this example, the `hello` resolver simply returns a greeting string.
3. **Apollo Server Initialization**: The `ApolloServer` class combines the schema and resolvers into a running GraphQL server.
—
## Adding More Complexity
Now, let’s add a more complex schema with data fetching.
### 1. Define a Schema for a Todo Application
const typeDefs = gql`
type Todo {
id: ID!
task: String!
completed: Boolean!
}
type Query {
todos: [Todo]
}
type Mutation {
addTodo(task: String!): Todo
toggleTodo(id: ID!): Todo
}
`;
—
### 2. Implement Resolvers
For data handling, we’ll use an in-memory array. In a real-world application, you’d use a database.
let todos = [
{ id: "1", task: "Learn GraphQL", completed: false },
{ id: "2", task: "Build an API", completed: true }
];
const resolvers = {
Query: {
todos: () => todos
},
Mutation: {
addTodo: (_, { task }) => {
const newTodo = { id: String(todos.length + 1), task, completed: false };
todos.push(newTodo);
return newTodo;
},
toggleTodo: (_, { id }) => {
const todo = todos.find(todo => todo.id === id);
if (!todo) throw new Error("Todo not found");
todo.completed = !todo.completed;
return todo;
}
}
};
—
### 3. Run the Server
Combine the schema and resolvers to run the Apollo Server.
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
—
## Testing the API
You can test the GraphQL API using Apollo Server’s built-in Playground. Run the server and navigate to the provided URL to execute queries like these:
### Fetch All Todos
—
### Add a New Todo
—
### Toggle Todo Completion
—
## Conclusion
GraphQL simplifies API development by providing a powerful query language and runtime. Using Apollo Server with Node.js, you can quickly build scalable and flexible APIs. This tutorial covered the basics, but you can expand upon this foundation by integrating databases, authentication, and more.
—