0
0
GraphQLquery~30 mins

Why server setup enables GraphQL - See It in Action

Choose your learning style9 modes available
Setting Up a Server to Enable GraphQL
📖 Scenario: You are building a simple server that will allow clients to request data using GraphQL. This server will manage data about books and authors.
🎯 Goal: Create a basic server setup that enables GraphQL queries to fetch book and author information.
📋 What You'll Learn
Create a data structure to hold books and authors
Define a configuration variable for the server port
Set up the GraphQL schema with types and queries
Complete the server setup to listen for requests
💡 Why This Matters
🌍 Real World
Setting up a GraphQL server is common in web development to provide flexible APIs for client applications.
💼 Career
Understanding server setup and GraphQL schema design is essential for backend developers working with modern APIs.
Progress0 / 4 steps
1
Create the initial data structure
Create a constant called books that is an array of objects with these exact entries: { id: '1', title: '1984', authorId: '1' }, { id: '2', title: 'Animal Farm', authorId: '1' }, and { id: '3', title: 'Brave New World', authorId: '2' }. Also create a constant called authors that is an array of objects with these exact entries: { id: '1', name: 'George Orwell' } and { id: '2', name: 'Aldous Huxley' }.
GraphQL
Hint

Use const to create arrays named books and authors with the exact objects.

2
Add server configuration variable
Create a constant called PORT and set it to 4000 to specify the server port number.
GraphQL
Hint

Use const PORT = 4000; to set the server port.

3
Define GraphQL schema with types and queries
Create a constant called typeDefs that defines a GraphQL schema string with types Book and Author. Include fields id and title for Book, and id and name for Author. Add a Query type with fields books returning a list of Book and authors returning a list of Author.
GraphQL
Hint

Use a template string to define typeDefs with the required GraphQL types and query fields.

4
Complete the server setup to listen for requests
Import ApolloServer from @apollo/server and create a new ApolloServer instance called server using typeDefs and resolvers that return the books and authors arrays for the books and authors queries. Then call server.listen({ port: PORT }) to start the server.
GraphQL
Hint

Import ApolloServer, define resolvers returning the data arrays, create the server instance, and start listening on the port.