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.

Hello World Service

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
  • Create a file name index.js in the folder.Get the needed functions from the apollo-server
const { ApolloServer, gql } = require('apollo-server');
  • Define the first Query type of hello: String in gql from the Apollo-Server library.
const typeDefs = gql`
    type Query {
        hello: String
    }
`;
  • Define the resolver (or the root as per in GraphQL Tutorial) to resolve the query given
const resolvers = {
    Query: {
        hello: () => {
            return 'Hello World!';
        }
    }
};
  • Lastly, instantiate the 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

Hello World for Apollo GraphQL
3.05 GEEK