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 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.
Key components of a GraphQL server:
- Schema: Defines data types and the shape of queries. E.g., a
Query
type with ahello
field that returns aString
. - Resolvers: Functions that fetch data as per the schema. E.g., the resolver for
hello
returns "Hello, GraphQL!".
When handling a query, the server:
- Validates the query.
- Resolves fields using resolvers.
- Returns the resulting data.
In this section, we'll set up a step-by-step basic GraphQL server.
-
Import Apollo Server and GraphQL types:
TypeScript1import { ApolloServer, gql } from 'apollo-server';
Load necessary modules to create and define the GraphQL server.
-
Define Schema:
TypeScript1const typeDefs = gql` 2 type Query { 3 hello: String 4 } 5`;
This defines a simple schema with a
Query
type that has a single fieldhello
, returning aString
. -
Define Resolvers:
TypeScript1const resolvers = { 2 Query: { 3 hello: () => 'Hello, GraphQL!', 4 }, 5};
The resolver for the
hello
field returns the string 'Hello, GraphQL!'. -
Initialize and Configure Apollo Server:
TypeScript1const server = new ApolloServer({ typeDefs, resolvers });
-
Start the Server:
TypeScript1server.listen().then(({ url }) => { 2 console.log(`🚀 Server ready at ${url}`); 3});
When you run the server file, it should print:
Plain text1🚀 Server ready at http://localhost:4000/
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.
-
Import Fetch Module:
TypeScript1import fetch from 'node-fetch';
This module helps in making HTTP requests to your server.
-
Define URL and Query:
TypeScript1const 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.
-
Create a Function to Execute the Query:
TypeScript1async 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:
JSON1{ 2 "data": { 3 "hello": "Hello, GraphQL!" 4 } 5}
This confirms the server correctly handles your query and provides the expected response.
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.