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.
We'll start by setting up a new Apollo Server instance to manage our GraphQL server. Let's do it step-by-step.
-
Define the GraphQL schema:
TypeScript1import { ApolloServer, gql } from 'apollo-server'; 2 3const typeDefs = gql` 4 type Book { 5 title: String 6 author: String 7 } 8 9 type Query { 10 books: [Book] 11 } 12`;
In this schema:
- The
Book
type hastitle
andauthor
fields, both of which are strings. - The
Query
type includes abooks
field that returns an array ofBook
objects.
- The
-
Create sample data:
TypeScript1const 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.
-
Define resolvers:
TypeScript1const resolvers = { 2 Query: { 3 books: () => books, 4 }, 5};
Here, the resolver for the
books
query simply returns thebooks
array we defined earlier. -
Initialize, configure, and start Apollo Server:
TypeScript1const server = new ApolloServer({ typeDefs, resolvers }); 2server.listen().then(({ url }) => { 3 console.log(`🚀 Server ready at ${url}`); 4});
Running this command will start the server and print the URL where it's accessible.
With the server running, let's write and execute a query to fetch the list of books.
TypeScript1import 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));
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:
JSON1{ 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.
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!