-
Architecture: REST is an architectural style using HTTP methods (GET, POST, PUT, DELETE) to interact with resources.
-
Data fetching: Each endpoint returns a fixed structure of data.
-
Over-fetching / Under-fetching:
- Over-fetching → client gets more data than needed.
- Under-fetching → client may need multiple requests to get all required data.
-
Caching: Easy via HTTP caching (GET requests can be cached).
-
Versioning: Often requires creating new endpoints for API version changes.
-
Error handling: Uses standard HTTP status codes (200, 404, 500, etc.).
// GET /users/1
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
res.json(user);
});-
Query Language: Developed by Facebook. Allows the client to specify exactly what data it needs.
-
Single endpoint: Usually
/graphqlinstead of multiple endpoints. -
Data fetching:
- Avoids over-fetching and under-fetching.
- Client can request nested data in a single query.
-
Strongly typed schema: Server defines a schema with types, queries, mutations, and subscriptions.
-
Versioning: No need for versioned endpoints; schema evolves with new fields.
-
Real-time support: Supports subscriptions for real-time data updates.
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type User {
id: ID
name: String
email: String
}
type Query {
user(id: ID!): User
}
`);
const root = {
user: ({ id }) => users.find(u => u.id === parseInt(id))
};
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // GraphiQL UI for testing
}));Query example:
query {
user(id: 1) {
name
email
}
}- Returns only the requested fields.
| Feature | REST | GraphQL |
|---|---|---|
| Endpoint | Multiple endpoints (/users, /posts) | Single endpoint (/graphql) |
| Data fetching | Fixed structure, may over/under-fetch | Flexible, client chooses fields |
| Versioning | Often requires new endpoints | Schema evolves, no version needed |
| Nested data | Requires multiple requests | Single query for nested data |
| Real-time | Needs WebSockets or separate setup | Supports subscriptions natively |
| Caching | Simple with HTTP caching | More complex, often handled client-side |
- REST → Simple APIs, predictable structure, widely adopted, easy caching.
- GraphQL → Complex apps, mobile apps needing flexible data, nested resources, fewer requests.