🟢 Node.js Q33 / 118

What is REST API?

AI-Powered Answer ✓ Answered

A REST API (Representational State Transfer Application Programming Interface) is a set of architectural principles for designing networked applications. It defines how clients and servers communicate using standard HTTP methods to perform operations on resources, making it a popular choice for building web services, especially with Node.js.

What is REST API?

REST, or Representational State Transfer, is an architectural style for developing web services. It's not a protocol or a standard, but rather a set of guidelines and constraints that, when followed, result in a system that can be easy to scale, maintain, and integrate with other systems. REST APIs enable communication between different software systems over the internet.

The core idea behind REST is to treat all data on the server as 'resources.' Each resource is identified by a unique URL (Uniform Resource Locator). Clients interact with these resources by sending standard HTTP requests to their URLs.

Key Principles of REST

  • Client-Server Architecture: Separation of concerns, meaning the client and server can evolve independently.
  • Statelessness: Each request from client to server must contain all the information necessary to understand the request. The server should not store any client context between requests.
  • Cacheability: Responses must explicitly or implicitly define themselves as cacheable to prevent clients from reusing stale or inappropriate data.
  • Uniform Interface: A fundamental constraint that simplifies the overall system architecture. It includes: Identification of resources, manipulation of resources through representations, self-descriptive messages, and HATEOAS (Hypermedia As The Engine Of Application State).
  • Layered System: A client cannot ordinarily tell whether it is connected directly to the end server or to an intermediary along the way.

Common HTTP Methods Used in REST

REST APIs leverage standard HTTP methods to perform CRUD (Create, Read, Update, Delete) operations on resources:

  • GET: Retrieves a resource or a collection of resources. (Read)
  • POST: Creates a new resource. (Create)
  • PUT: Updates an existing resource or creates one if it doesn't exist. (Update)
  • DELETE: Removes a resource. (Delete)
  • PATCH: Partially updates an existing resource.

REST API with Node.js

Node.js is an excellent choice for building RESTful APIs due to its non-blocking, event-driven architecture, which makes it highly efficient for I/O-bound operations typical in web services. Its JavaScript-centric ecosystem also allows for full-stack JavaScript development.

Frameworks like Express.js simplify the process of creating REST APIs in Node.js by providing robust routing, middleware, and other features. Other frameworks like Hapi.js and Koa.js are also popular alternatives.

javascript
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json()); // For parsing application/json

let items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' }
];

// GET all items
app.get('/api/items', (req, res) => {
    res.json(items);
});

// GET a single item by ID
app.get('/api/items/:id', (req, res) => {
    const item = items.find(i => i.id === parseInt(req.params.id));
    if (!item) return res.status(404).send('Item not found.');
    res.json(item);
});

// POST a new item
app.post('/api/items', (req, res) => {
    const newItem = {
        id: items.length + 1,
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json(newItem);
});

// PUT to update an item
app.put('/api/items/:id', (req, res) => {
    let item = items.find(i => i.id === parseInt(req.params.id));
    if (!item) return res.status(404).send('Item not found.');

    item.name = req.body.name;
    res.json(item);
});

// DELETE an item
app.delete('/api/items/:id', (req, res) => {
    const initialLength = items.length;
    items = items.filter(i => i.id !== parseInt(req.params.id));
    if (items.length === initialLength) return res.status(404).send('Item not found.');
    res.status(204).send(); // No Content
});

app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});

Advantages of REST APIs

  • Simplicity and Readability: Uses standard HTTP methods and URLs, making it intuitive to understand and interact with.
  • Scalability: Statelessness allows for easy distribution of requests across multiple servers.
  • Flexibility and Portability: The client-server separation means clients and servers can be developed and updated independently, using different technologies.
  • Widespread Adoption: Supported by virtually all programming languages and platforms, making integration straightforward.
  • Performance: Can be optimized with caching mechanisms.

Disadvantages of REST APIs

  • Over-fetching/Under-fetching: Clients often receive more data than needed (over-fetching) or require multiple requests to get all necessary data (under-fetching), which can impact performance.
  • Lack of Real-time Push: REST is inherently request-response based and doesn't natively support real-time, two-way communication (like WebSockets).
  • Statelessness Overhead: Every request must carry all necessary information, which can add overhead compared to stateful protocols.
  • Complexity for Simple APIs: For very simple APIs, the full REST architectural style might be overkill.