This video is available to students only

Build a GraphQL Schema And Test it in GraphQL Playground

In this lesson, we'll use the Apollo Server and GraphQL JavaScript libraries to create a minimal GraphQL API that we'll be able to interact within an IDE known as GraphQL Playground.

Creating a GraphQL Schema with the GraphQL JS Library#

📝 This lesson's quiz can be found - here.
🗒️ Solutions for this lesson's quiz can be found - here.


Let's quickly summarize how we want to introduce Apollo Server before we begin doing so.

To introduce Apollo server to our application, the first thing we'll need to do is create an instance of Apollo server. This is done by importing the ApolloServer class and constructing a new instance with the ApolloServer constructor.

With an Apollo Server instance created, the apollo-server-express library allows us to specify middleware that works alongside the existing server middleware. It's in this middleware where we can pass in the express app instance as well as specify the endpoint for where our GraphQL API should live.

The ApolloServer() constructor can take in a series of options needed to instantiate the Apollo Server instance. The conventional options that can often be passed in are the:

  • typeDefs: String that represents the entire GraphQL schema.

  • resolvers: Map of functions that implement the schema.

Though we're going to aim to get to this point, we'll begin by going through a more "bare-bones" approach to creating a GraphQL server. In the first attempt to creating our schema, we'll import and create GraphQLObjectType's with the help of the graphql JavaScript library.

Simple GraphQL Schema#

To begin, we'll have the ApolloServer constructor class imported in our /src/index.ts file. We'll run the constructor function and assign the result to a server const variable. We won't pass in any arguments to the constructor just yet. We'll apply middleware to the Apollo Server instance and pass in the express app instance, and state our GraphQL API will be on a path of /api.

Finally, we'll also remove all the RESTful Express Routes we've created since we'll now be moving towards GraphQL. We'll remove the import of listings as well as remove the import and use of bodyParser.

At this moment, our src/index.ts file will look like the following:

Let's now look to create a schema with the graphql JavaScript library. We'll build our schema within a new file called graphql.ts that is to be created in our src/ folder.

To create our schema, we'll be using class objects that the graphql JavaScript library provides. We're going to begin by importing two classes from the graphql library GraphQLSchema and GraphQLObjectType.

Start a new discussion. All notification go to the author.