0
0
Expressframework~30 mins

REST vs GraphQL awareness in Express - Hands-On Comparison

Choose your learning style9 modes available
REST vs GraphQL Awareness with Express
📖 Scenario: You are building a simple Express server to understand the difference between REST and GraphQL APIs. This will help you see how data can be requested and served in two different ways.
🎯 Goal: Create an Express server that has one REST endpoint and one GraphQL endpoint. The REST endpoint will return a list of books, and the GraphQL endpoint will allow querying the same books with flexible fields.
📋 What You'll Learn
Create an array called books with 3 book objects, each having id, title, and author properties
Create a variable called port set to 4000
Create a REST GET endpoint at /books that returns the books array as JSON
Set up a GraphQL schema with a Book type and a books query that returns the list of books
💡 Why This Matters
🌍 Real World
APIs are how apps talk to each other. REST and GraphQL are two popular ways to build APIs. Understanding both helps you choose the right tool for your project.
💼 Career
Many jobs require building or working with APIs. Knowing REST and GraphQL basics is essential for backend and full-stack developers.
Progress0 / 4 steps
1
DATA SETUP: Create the books array
Create an array called books with these exact 3 objects: { id: 1, title: '1984', author: 'George Orwell' }, { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien' }, and { id: 3, title: 'Fahrenheit 451', author: 'Ray Bradbury' }.
Express
Need a hint?

Use const books = [ ... ] with the exact objects inside.

2
CONFIGURATION: Set the server port
Create a variable called port and set it to 4000.
Express
Need a hint?

Use const port = 4000; to set the port number.

3
CORE LOGIC: Create the REST GET endpoint
Create an Express app with const app = express(). Then add a GET endpoint at /books that sends the books array as JSON using res.json(books).
Express
Need a hint?

Use const app = express() and app.get('/books', (req, res) => res.json(books)).

4
COMPLETION: Add GraphQL schema and endpoint
Import graphqlHTTP from express-graphql and buildSchema from graphql. Create a GraphQL schema with a Book type having id, title, and author fields. Add a books query returning the list of books. Then add a GraphQL endpoint at /graphql using app.use with graphqlHTTP, passing the schema and a root resolver that returns books. Finally, start the server listening on port with app.listen(port).
Express
Need a hint?

Use buildSchema to define the schema and graphqlHTTP middleware for the /graphql route.