REST and GraphQL are two ways to get data from a server. They help your app talk to the backend and show information to users.
REST vs GraphQL awareness in Express
/* REST example: Express GET endpoint */ app.get('/users/:id', (req, res) => { const userId = req.params.id; // fetch user by userId res.json(userData); }); /* GraphQL example: Single endpoint with query */ const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const schema = buildSchema(` type Query { user(id: ID!): User } type User { id: ID name: String email: String } `); const root = { user: ({ id }) => { // fetch user by id } }; app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, }));
REST uses multiple URLs for different data types and actions.
GraphQL uses one URL and lets clients specify what data they want in a query.
/* REST: Get user by ID */ GET /users/123 /* REST: Get all users */ GET /users
/* GraphQL: Query user by ID */ { user(id: "123") { id name } }
/* REST: Update user email */ PUT /users/123 { "email": "new@example.com" }
/* GraphQL: Mutation to update user email */ mutation { updateUser(id: "123", email: "new@example.com") { id email } }
This program shows both REST and GraphQL ways to get user data by ID. You can try REST by visiting /users/1 or GraphQL by sending a query to /graphql.
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const app = express(); app.use(express.json()); // Sample data const users = [ { id: '1', name: 'Alice', email: 'alice@example.com' }, { id: '2', name: 'Bob', email: 'bob@example.com' } ]; // REST endpoint to get user by ID app.get('/users/:id', (req, res) => { const userId = req.params.id; const user = users.find(u => u.id === userId); if (user) { res.json(user); } else { res.status(404).json({ error: 'User not found' }); } }); // GraphQL schema const schema = buildSchema(` type User { id: ID name: String email: String } type Query { user(id: ID!): User } `); // Root resolver const root = { user: ({ id }) => users.find(u => u.id === id) }; // GraphQL endpoint app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true })); // Start server app.listen(4000, () => { console.log('Server running on http://localhost:4000'); console.log('Try REST: GET http://localhost:4000/users/1'); console.log('Try GraphQL: http://localhost:4000/graphql'); });
REST is simple and works well for fixed data needs but can send extra data you don't want.
GraphQL lets clients ask for exactly what they need, reducing data transfer.
GraphQL requires learning query language and setting up a schema, which can be more complex.
REST uses multiple URLs and HTTP methods to get and change data.
GraphQL uses one URL and lets clients specify exactly what data they want.
Choose REST for simple APIs and GraphQL for flexible, efficient data fetching.