Lesson 1
Setting Up a Basic GraphQL Server
Lesson Overview

Welcome to the first lesson of our "Introduction to GraphQL and Apollo Server" course! In this lesson, we will introduce you to GraphQL and Apollo Server and guide you through setting up a basic GraphQL server.

GraphQL and Apollo Server

GraphQL is a query language for APIs that allows you to request only the data you need, unlike REST, which often requires multiple endpoints. Apollo Server is a popular, GraphQL-compliant server known for its simplicity and active support. Other tools available include:

  • Express-GraphQL: Flexible GraphQL server for Express applications.
  • Relay: JavaScript framework for efficient data fetching with GraphQL.
Basic Structure of a GraphQL Server

Key components of a GraphQL server:

  • Schema: Defines data types and the shape of queries. E.g., a Query type with a hello field that returns a String.
  • Resolvers: Functions that fetch data as per the schema. E.g., the resolver for hello returns "Hello, GraphQL!".

When handling a query, the server:

  1. Validates the query.
  2. Resolves fields using resolvers.
  3. Returns the resulting data.
Creating the Basic GraphQL Server

In this section, we'll set up a step-by-step basic GraphQL server.

  1. Import Apollo Server and GraphQL types:

    TypeScript
    1import { ApolloServer, gql } from 'apollo-server';

    Load necessary modules to create and define the GraphQL server.

  2. Define Schema:

    TypeScript
    1const typeDefs = gql` 2 type Query { 3 hello: String 4 } 5`;

    This defines a simple schema with a Query type that has a single field hello, returning a String.

  3. Define Resolvers:

    TypeScript
    1const resolvers = { 2 Query: { 3 hello: () => 'Hello, GraphQL!', 4 }, 5};

    The resolver for the hello field returns the string 'Hello, GraphQL!'.

  4. Initialize and Configure Apollo Server:

    TypeScript
    1const server = new ApolloServer({ typeDefs, resolvers });
  5. Start the Server:

    TypeScript
    1server.listen().then(({ url }) => { 2 console.log(`🚀 Server ready at ${url}`); 3});

    When you run the server file, it should print:

    Plain text
    1🚀 Server ready at http://localhost:4000/
Querying the Server

Now that your server is running, let's query it to test if everything works correctly by doing some querying to the server in a separate file.

  1. Import Fetch Module:

    TypeScript
    1import fetch from 'node-fetch';

    This module helps in making HTTP requests to your server.

  2. Define URL and Query:

    TypeScript
    1const url = 'http://localhost:4000/'; 2const query = ` 3 query { 4 hello 5 } 6`;

    Specify the URL of your GraphQL server and the query you want to run.

  3. Create a Function to Execute the Query:

    TypeScript
    1async function fetchGraphQLData() { 2 try { 3 const response = await fetch(url, { 4 method: 'POST', 5 headers: { 6 'Content-Type': 'application/json', 7 }, 8 body: JSON.stringify({ query }), 9 }); 10 11 const data = await response.json(); 12 console.log(JSON.stringify(data, null, 2)); 13 } catch (error) { 14 console.error('Error:', error); 15 } 16} 17 18fetchGraphQLData();

    Running this function should give you the output:

    JSON
    1{ 2 "data": { 3 "hello": "Hello, GraphQL!" 4 } 5}

This confirms the server correctly handles your query and provides the expected response.

Lesson Summary

Up next, you'll practice creating more complex schemas and queries. This hands-on practice will solidify your understanding and prepare you for advanced topics.

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