Here's how to create a Node.js RESTful API endpoint to serve a GraphQL API using Apollo Server:
š Setting Up Your Node.js Project
First, initialize your Node.js project and install the necessary packages:
mkdir graphql-api
cd graphql-api
npm init -y
npm install apollo-server express graphql
āļø Creating the Express Server
Next, set up your Express server. This will act as the RESTful endpoint.
// index.js
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');
const app = express();
async function startApolloServer() {
const server = new ApolloServer({
typeDefs,
resolvers,
});
await server.start();
server.applyMiddleware({ app, path: '/graphql' });
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}/graphql`);
});
}
startApolloServer();
š Defining the GraphQL Schema
Create your GraphQL schema. This includes type definitions and resolvers.
// schema.js
const { gql } = require('apollo-server-express');
// Type definitions (schema)
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
// Resolvers
const resolvers = {
Query: {
books: () => {
return [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' },
];
},
},
};
module.exports = { typeDefs, resolvers };
š Connecting Apollo Server to Express
In the main `index.js` file, Apollo Server is connected as middleware to the Express app.
ā¶ļø Running the Application
To run the application, execute:
node index.js
This will start the server, and you can access the GraphQL API at `http://localhost:4000/graphql`.
ā
Summary
- ā
Initialize a Node.js project.
- ā
Install necessary packages (apollo-server-express, express, graphql).
- ā
Create an Express server.
- ā
Define your GraphQL schema (type definitions and resolvers).
- ā
Connect Apollo Server to the Express app as middleware.
- ā
Run the application.
This setup provides a RESTful endpoint (`/graphql`) that serves your GraphQL API using Apollo Server.