Schema Development Tutorials, Guides & Insights
Unlock 2+ expert-curated schema tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your schema skills on DeveloperBreeze.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
Tutorial
javascript nodejs +1
Building a GraphQL API with Node.js and Apollo Server
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 aBooktype and operations to query all books and add a new book. - Resolvers: These functions handle the logic for fetching and manipulating data. The
Queryresolver fetches the list of books, and theMutationresolver adds a new book to the list. - Apollo Server: Integrates with Express to handle incoming requests and execute GraphQL queries.
Aug 12, 2024
Read More Code
nodejs graphql
GraphQL API Server with Node.js and Apollo Server
mkdir graphql-server
cd graphql-server
npm init -yInstall the required packages:
Aug 12, 2024
Read More