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 using Apollo Server 4. Let's proceed step-by-step.
-
Define the GraphQL schema:
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:
This array will act as our in-memory database of books.
-
Define resolvers:
Here, the resolver for the
books
query simply returns thebooks
array we defined earlier. -
Initialize, configure, and start Apollo Server:
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.
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:
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!
