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

Use Postman or curl:

curl http://localhost:3000

Apr 04, 2025
Read More
Tutorial

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

  • Encryption: Store sensitive data, such as private keys, in an encrypted format.
  • Access Controls: Limit who and what can access the database.
  • Use environment variables or configuration files to manage sensitive information instead of hardcoding them in your source code.

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

This cheatsheet offers a broad overview of the most widely-used libraries in the React ecosystem. These libraries cover various aspects of React development, from state management and UI components to testing and animations, helping you build robust and maintainable applications. Whether you're a beginner or an experienced developer, integrating these tools into your workflow can significantly enhance your productivity and the quality of your React projects.

Aug 21, 2024
Read More

Discussion 0

Please sign in to join the discussion.

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