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

After 100 requests within an hour, you’ll get:

{
  "error": "Too many requests. Try later."
}

Apr 04, 2025
Read More
Tutorial

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

This command creates a package.json file with default configurations.

To interact with SQLite databases, install the sqlite3 package using npm:

Oct 24, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

Introduction

REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol, usually HTTP. RESTful APIs are widely used due to their simplicity and scalability. This comprehensive cheatsheet covers essential REST API principles and operations, complete with examples presented in HTML tables for easy reference.

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!