How to Create Schema in Apollo Server: Simple Guide
To create a schema in Apollo Server, define your GraphQL types using
typeDefs with the gql template literal, then provide resolver functions in resolvers. Finally, pass both to the ApolloServer constructor to set up your GraphQL API.Syntax
The schema in Apollo Server is created by defining typeDefs and resolvers. typeDefs describe the data types and queries using GraphQL schema language. resolvers are JavaScript functions that tell Apollo Server how to fetch or compute the data for each field.
javascript
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello world!' } }; const server = new ApolloServer({ typeDefs, resolvers });
Example
This example shows a complete Apollo Server setup with a simple schema that has one query hello returning a string. It demonstrates how to define the schema and resolvers, then start the server.
javascript
const { ApolloServer, gql } = require('apollo-server'); // Define schema with one query const typeDefs = gql` type Query { hello: String } `; // Provide resolver for the query const resolvers = { Query: { hello: () => 'Hello world!' } }; // Create Apollo Server instance const server = new ApolloServer({ typeDefs, resolvers }); // Start the server server.listen().then(({ url }) => { console.log(`🚀 Server ready at ${url}`); });
Output
🚀 Server ready at http://localhost:4000/
Common Pitfalls
- Forgetting to wrap your schema string with
gqlcauses errors because Apollo Server expects parsed schema. - Not matching resolver names exactly with schema fields leads to missing data.
- Omitting the
Querytype or defining queries incorrectly will break the schema. - Not starting the server with
server.listen()means your API won't be accessible.
javascript
/* Wrong: Missing gql wrapper */ const typeDefsWrong = ` type Query { hello: String } `; /* Right: Use gql to parse schema */ const typeDefs = gql` type Query { hello: String } `;
Quick Reference
Remember these key parts when creating a schema in Apollo Server:
- typeDefs: Define your GraphQL types and queries using
gql. - resolvers: Provide functions to fetch or compute data for each query or field.
- ApolloServer: Pass
typeDefsandresolversto create the server. - Start server: Use
server.listen()to run your API.
Key Takeaways
Define your schema with
typeDefs using the gql template literal.Write resolver functions matching your schema fields to provide data.
Create an
ApolloServer instance with typeDefs and resolvers.Start the server with
server.listen() to make your API available.Always ensure resolver names exactly match schema fields to avoid errors.