DeveloperBreeze

GraphQL API Server with Node.js and Apollo Server

Setting Up the Server

  1. 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
  1. Install Dependencies

Install the required packages:

   npm install express apollo-server-express graphql
  1. 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 a Book 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

  1. Start the Server

Run the server using Node.js:

   node index.js
  1. 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.

  1. 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.

Related Posts

More content you might like

Tutorial

Build a Custom Rate Limiter in Node.js with Redis

When developing web apps or APIs, it’s critical to prevent users from overwhelming your server. That’s where rate limiting comes in. In this guide, we’ll build a custom rate limiter in Node.js using Redis—no libraries, no magic, just code you control and understand.

  • How to use Redis to count and throttle requests
  • How to implement reusable middleware in Express
  • How to rate limit by IP or API key
  • Why this method is better for learning and customization

Apr 04, 2025
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

Connected to the SQLite database.
Table "accounts" created or already exists.
A row has been inserted with rowid 1
Private Key: private_key_value
Address: address_value
Decimal Number: decimalNumber_value
Has Transactions: 1
---------------------------
Database connection closed.

For your convenience, here's the complete app.js file combining all the steps:

Oct 24, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 24, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!