Image for post
Image for post

📄 Table of Contents

  • Get started with Apollo Server
  • Build a GraphQL Server from Scratch using Express- (Part 1)

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Apollo Server is a library that helps you connect a GraphQL schema to an HTTP server in Node. js. It’s possible to use Apollo Server with all popular HTTP servers like Express, Connect, Hapi, Koa, Restify, and Lambda. In this tutorial you’ll learn how to set up Apollo Server with Node. js and Express.

Get started with Apollo Server

This tutorial walks you through installing and configuring Apollo Server. If you’re just getting started with GraphQL or the Apollo platform, we recommend first completing the full-stack tutorial.

This tutorial helps you:

  • Obtain a basic understanding of GraphQL principles
  • Define a GraphQL schema that represents the structure of your data set
  • Run an instance of Apollo Server that lets you execute queries against your schema

This tutorial assumes that you are familiar with the command line and JavaScript, and that you have a recent version of Node.js (8+) installed.

Create a new project & install dependencies

* mkdir demo
* cd demo
* npm init --yes → creates package.json
* npm install apollo-server graphql
* touch index.js

Define your GraphQL schema

Open index.js in your preferred editor and paste the following into it. Below snippet defines a simple, valid GraphQL schema. Clients will be able to execute a query named books, and our server will return an array of zero or more Books.

const { ApolloServer, gql } = require('apollo-server');// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
# Comments in GraphQL strings (such as this one) start with the hash (#) symbol. # This "Book" type defines the queryable fields for every book in our data source.const typeDefs = gql`
type Book {
title: String
author: String
}
# The "Query" type is special: it lists all of the available queries that
# clients can execute, along with the return type for each. In this
# case, the "books" query returns an array of zero or more Books (defined above).
type Query {
books: [Book]
}
`;

Define your data set

Apollo Server can fetch data from any source you connect to (including a database, a REST API, a static object storage service, or even another GraphQL server). For the purposes of this tutorial, we’ll just hardcode some example data.

Add the following to the bottom of index.js:

const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];

Define a resolver

Resolvers tell Apollo Server how to fetch the data associated with a particular type. Because our Book array is hardcoded, the corresponding resolver is straightforward.

Add the following to the bottom of index.js:

// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
};

Create an instance of ApolloServer

We’ve defined our schema, data set, and resolver. Now we just need to provide this information to Apollo Server when we initialize it.

Add the following to the bottom of index.js:

// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });// The `listen` method launches a web server.server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});

Start the server

node index.js

You should see the following output:

🚀 Server ready at http://localhost:4000/

Execute your first query

We can now execute GraphQL queries on our server. To execute our first query, we’ll use a tool called GraphQL Playground.

With your server still running, visit http://localhost:4000 in your browser to open GraphQL Playground. (Apollo Server hosts GraphQL Playground automatically when you run it in development.)

Here’s a GraphQL query string for executing the books query:

{
books {
title
author
}
}

Paste this string into the left text area and click the Play button. The results (from our hardcoded data set) appear on the right:

Image for post
Image for post

One of the most important concepts of GraphQL is that clients can choose to query only for the fields they need. Delete author from the query string and execute it again. The response updates to include only the title field for each book!

Build a GraphQL Server from Scratch using Express- (Part 1)

References:

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store