GraphQL course defining a schema

Im going to expose an API over HTTP that is the most common way to use GraphQL and we are going to use Apollo server that is a project that makes easy to setup a GraphQL server in Javascript with Nodejs.

In our terminal let’s install apollo-server and graphql, so the graphql package contains the graph core functionality & apollo server is for serving over HTTP.

Then let’s create our server configuration:

First we are going to create a schema that will describe what our API can do, so we are going to keep it in a variable called typeDef and inside we are going to use a special language called the GraphQL schema definition language:

const typeDefs = `
    type Query {
        greeting: String
    }
`;

In Schema we always need a schema type that contains all possible queries that can be make by a client when calling the server.

So, now we can parse the schema using the function called gql that is coming from the apollo-server module.

gql is a type function that means that we can use it to tag a template literal, in other words we put gql before the delimiter string.

const { gql } = require("apollo-server");

const typeDefs = gql`

Now I’m going to console the typeDef & run node server.js in the terminal to check what this variable have

console.log(typeDefs);

So, the string that at we wrote at the beginning now was parse into some type of object that represent the GraphQL schema.

Also if we have a mistake when we write our schema, for example if instead of type we wrote class, then the gql function will fail when parse:

Then gql will said:

Nice, so now we have our schema definition ready.

Final server.js file

const { gql } = require("apollo-server");

const typeDefs = gql`
  type Query {
    greeting: String
  }
`;

console.log(typeDefs);

By Cristina Rojas.