Skip to content

Latest commit

 

History

History
97 lines (74 loc) · 3.08 KB

File metadata and controls

97 lines (74 loc) · 3.08 KB

1. REST (Representational State Transfer)

  • 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.).

Example (Express.js REST)

// GET /users/1
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  res.json(user);
});

2. GraphQL

  • Query Language: Developed by Facebook. Allows the client to specify exactly what data it needs.

  • Single endpoint: Usually /graphql instead 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.

Example (GraphQL Node.js using express-graphql)

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.

3. Key Differences

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

When to Use

  • REST → Simple APIs, predictable structure, widely adopted, easy caching.
  • GraphQL → Complex apps, mobile apps needing flexible data, nested resources, fewer requests.