web-development backend-development javascript nodejs data-fetching graphql apollo-server express api-server mutations
GraphQL API Server with Node.js and Apollo Server
This snippet demonstrates how to set up a basic GraphQL server using Apollo Server and Express in Node.js. The server will expose a simple API for managing a list of books.
Setting Up the Server
- Initialize the Project
First, create a new directory for your project and initialize it with npm:
mkdir graphql-server
cd graphql-server
npm init -y
- Install Dependencies
Install the required packages:
npm install express apollo-server-express graphql
- Create the Server Code
Create an index.js
file and add the following code:
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
// Sample data
let books = [
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee' },
];
// GraphQL schema definition
const typeDefs = gql`
type Book {
title: String!
author: String!
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String!, author: String!): Book
}
`;
// GraphQL resolvers
const resolvers = {
Query: {
books: () => books,
},
Mutation: {
addBook: (_, { title, author }) => {
const newBook = { title, author };
books.push(newBook);
return newBook;
},
},
};
// Create Apollo server
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
Features of the GraphQL Server
- Schema Definition: The
typeDefs
defines a simple schema with aBook
type and queries to fetch books and add a new book.
- Resolvers: Functions that resolve the queries and mutations. In this case, they return all books and add a new book to the list.
How to Use
- Start the Server
Run the server using Node.js:
node index.js
- Access the GraphQL Playground
Open a browser and go to http://localhost:4000/graphql
. You'll see the Apollo GraphQL Playground, where you can test your queries and mutations.
- Example Queries
- Fetch Books
query {
books {
title
author
}
}
- Add a Book
mutation {
addBook(title: "1984", author: "George Orwell") {
title
author
}
}
Benefits of GraphQL
- Flexible Queries: Allows clients to request only the data they need, reducing over-fetching.
- Strongly Typed: Ensures data consistency and helps with error handling.
- Single Endpoint: All data operations occur through a single endpoint, simplifying network requests.
Comments
Please log in to leave a comment.