DeveloperBreeze

Apollo Server Development Tutorials, Guides & Insights

Unlock 2+ expert-curated apollo server tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your apollo server skills on DeveloperBreeze.

Building a GraphQL API with Node.js and Apollo Server

Tutorial August 12, 2024
javascript nodejs graphql

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}`)
);
  • Schema Definition (typeDefs): This defines the types and operations available in the API. We define a Book type and operations to query all books and add a new book.
  • Resolvers: These functions handle the logic for fetching and manipulating data. The Query resolver fetches the list of books, and the Mutation resolver adds a new book to the list.
  • Apollo Server: Integrates with Express to handle incoming requests and execute GraphQL queries.

GraphQL API Server with Node.js and Apollo Server

Code August 12, 2024
nodejs graphql

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

Run the server using Node.js: