G
raphQL is an API service interface that’s getting more and more popular. The official GraphQL page provides an excellent tutorial, starting with a very simple Hello World Example.There’s a popular library named Apollo that wraps around GraphQL with better interfaces to provide a full-stack solution. However, it’s tutorial started with a relatively complicated example.Hence I’m blogging here to provide the simple Hello World Example on Apollo, to gap the basics of GraphQL and Apollo.
This is based on the tutorial here, except that it is using Apollo-Server instead of Express and GraphQL library directly.Install Apollo-Server library, using the below command in a folder.
yarn add apollo-server
apollo-server
const { ApolloServer, gql } = require('apollo-server');
hello: String
in gql
from the Apollo-Server library.const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => {
return 'Hello World!';
}
}
};
ApolloServer
and you’ll start the service.const server = new ApolloServer({typeDefs, resolvers})
server.listen(4000).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
The entire code as below
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => {
return 'Hello World!';
}
}
};
const server = new ApolloServer({typeDefs, resolvers})
server.listen(4000).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
You just start it using
node index.js
You can now look at the browser as below.
#nodejs #web-development #graphql-apollo-server #graphql