Lesson 2
Building a Basic GraphQL Server with Apollo Server 4
Introduction to GraphQL and Apollo Server

In this lesson, we will define basic types and write simple queries in GraphQL using Apollo Server. By the end, you'll create a basic GraphQL server to fetch a list of books, building on what you've learned about setting up a GraphQL server.

Creating the Server with Apollo Server

We'll start by setting up a new Apollo Server instance to manage our GraphQL server using Apollo Server 4. Let's proceed step-by-step.

  1. Define the GraphQL schema:

    JavaScript
    1import { ApolloServer } from '@apollo/server'; 2import { startStandaloneServer } from '@apollo/server/standalone'; 3 4const typeDefs = `#graphql 5 type Book { 6 title: String 7 author: String 8 } 9 10 type Query { 11 books: [Book] 12 } 13`;

    In this schema:

    • The Book type has title and author fields, both of which are strings.
    • The Query type includes a books field that returns an array of Book objects.
  2. Create sample data:

    JavaScript
    1const books = [ 2 { title: 'The Hobbit', author: 'J.R.R. Tolkien' }, 3 { title: 'Harry Potter', author: 'J.K. Rowling' }, 4];

    This array will act as our in-memory database of books.

  3. Define resolvers:

    JavaScript
    1const resolvers = { 2 Query: { 3 books: () => books, 4 }, 5};

    Here, the resolver for the books query simply returns the books array we defined earlier.

  4. Initialize, configure, and start Apollo Server:

    JavaScript
    1const server = new ApolloServer({ typeDefs, resolvers }); 2 3const { url } = await startStandaloneServer(server, { 4 listen: { port: 4000 }, 5}); 6 7console.log(`🚀 Server ready at ${url}`);

    Running this command will start the server and print the URL where it's accessible.

Running Queries Against the Server

With the server running, let's write and execute a query to fetch the list of books.

JavaScript
1import fetch from 'node-fetch'; 2 3const query = ` 4 query { 5 books { 6 title 7 author 8 } 9 } 10`; 11 12const url = 'http://localhost:4000/'; 13 14fetch(url, { 15 method: 'POST', 16 headers: { 17 'Content-Type': 'application/json', 18 }, 19 body: JSON.stringify({ query }), 20}) 21 .then((response) => response.json()) 22 .then((data) => console.log(JSON.stringify(data, null, 2))) 23 .catch((error) => console.error('Error:', error));

When a query is sent to the GraphQL server:

  • The server parses the query to ensure it matches the schema.
  • The server validates the query to check for any syntax errors or mismatched fields.
  • The server executes the resolver associated with the query field (books).
  • The data returned by the resolver is formatted into a JSON response and sent back to the client.

This script:

  • Sends a POST request to the server with a query to fetch books.
  • Logs the response, which should include the list of books with their titles and authors.

The script outputs:

JSON
1{ 2 "data": { 3 "books": [ 4 { 5 "title": "The Hobbit", 6 "author": "J.R.R. Tolkien" 7 }, 8 { 9 "title": "Harry Potter", 10 "author": "J.K. Rowling" 11 } 12 ] 13 } 14}

This output confirms that our server correctly handles the query and returns the expected data.

Lesson Summary

In this lesson, we:

  • Created a schema with a basic type (Book).
  • Set up resolvers to fetch data.
  • Wrote and ran queries to retrieve a list of books.

Next, you will practice what you've learned by tackling exercises that help solidify these concepts. The following lessons will cover more complex queries and mutations.

Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.