Implementing a Basic GraphQL API with Node.js, Express, and Apollo Server
Implementing a GraphQL API involves several steps, from designing your schema to setting up the server and writing resolvers. Below, I’ll outline a basic structure and provide code snippets to help you get started.
1. Designing the Schema
The schema defines the structure of the data that can be queried. It specifies the types, queries, mutations, and subscriptions available in the API.
# schema.graphql
type Query {
getUser(id: ID!): User
listUsers: [User]
}
type Mutation {
createUser(name: String!, email: String!): User
updateUser(id: ID!, name: String, email: String): User
}
type User {
id: ID!
name: String!
email: String!
}
2. Setting Up the Server
You’ll need to set up a server to handle GraphQL requests. Here, I’ll use Express
and Apollo Server
for a Node.js environment.
Install Dependencies
npm install express apollo-server-express graphql
Server Setup
// index.js
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');
const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () => {
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
});
3. Resolvers
Resolvers are the functions that handle the logic for fetching or modifying data.
// resolvers.js
const users = [];
const resolvers = {
Query: {
getUser: (parent, args) => users.find(user => user.id === args.id),
listUsers: () => users,
},
Mutation: {
createUser: (parent, args) => {
const newUser = { id: `${users.length + 1}`, ...args };
users.push(newUser);
return newUser;
},
updateUser: (parent, args) => {
const index = users.findIndex(user => user.id === args.id);
if (index === -1) return null;
const updatedUser = { ...users[index], ...args };
users[index] = updatedUser;
return updatedUser;
},
},
};
module.exports = resolvers;
4. Type Definitions
Type definitions specify the schema in your JavaScript file.
// typeDefs.js
const { gql } = require('apollo-server-express');
const typeDefs = gql`
type Query {
getUser(id: ID!): User
listUsers: [User]
}
type Mutation {
createUser(name: String!, email: String!): User
updateUser(id: ID!, name: String, email: String): User
}
type User {
id: ID!
name: String!
email: String!
}
`;
module.exports = typeDefs;
5. Running the Server
With everything set up, you can run your server and start interacting with your GraphQL API.
node index.js
Now, you can navigate to http://localhost:4000/graphql
to access the GraphQL Playground, where you can test your queries and mutations.
6. Example Queries and Mutations
Query:
query {
listUsers {
id
name
email
}
}
Mutation:
mutation {
createUser(name: "John Doe", email: "john.doe@example.com") {
id
name
email
}
}
This basic setup can be expanded with features like authentication, authorization, data validation, and more, depending on the needs of your application.