GraphQL - Building a GraphQL API
Step-by-Step Guide to Building a GraphQL API
This guide walks you through the process of creating a GraphQL API from scratch, using Node.js and Apollo Server.
Key Points:
- Understand the fundamentals of GraphQL.
- Set up a basic Node.js server.
- Define your schema and resolvers.
Setting Up Your Environment
Begin by setting up a new Node.js project. Run the following commands:
mkdir graphql-api
cd graphql-api
npm init -y
npm install apollo-server graphql
Creating Your First Server
Create a file named server.js
and set up your Apollo Server.
const { ApolloServer, gql } = require('apollo-server');
// Define your schema
const typeDefs = gql`
type Query {
hello: String
}
`;
// Define your resolvers
const resolvers = {
Query: {
hello: () => 'Hello, world!',
},
};
// Create the server
const server = new ApolloServer({ typeDefs, resolvers });
// Start the server
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Defining a Schema
Expand your schema to include more complex types. For example, define a User
type.
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
}
type Query {
users: [User]
}
`;
Adding Resolvers
Add resolvers to handle your queries. For example, create a mock list of users.
const resolvers = {
Query: {
users: () => [
{ id: '1', name: 'John Doe', email: 'john.doe@example.com' },
{ id: '2', name: 'Jane Smith', email: 'jane.smith@example.com' },
],
},
};
Testing Your API
You can test your GraphQL API using tools like GraphQL Playground or Postman. Simply query the users
field.
query {
users {
id
name
email
}
}
Conclusion
You have successfully built a basic GraphQL API! From here, you can expand your API by adding mutations, authentication, and connecting to a database.