JavaScript REST API with Live Project

JavaScript REST API with Live Project

A JavaScript REST API is a way for programs to talk to each other using the rules of REST and the JavaScript language. REST is a set of guidelines that use normal web actions (GET, POST, PUT, DELETE) to help computers communicate. JavaScript is a popular language for working with REST APIs, both on websites and in server environments like Node.js.

To make it easier to understand, let's look at a simple example. We'll build a basic Task Management API using Node.js and Express. This API will let you create, read, update, and delete tasks.

  1. Set Up the Project: Start by setting up your project. Initialize a Node.js project and install the necessary dependencies:

     npm init -y
     npm install express body-parser
    
  2. Create the Server and Routes: Create a server.js file and set up the Express server with routes for handling tasks:

     // server.js
     const express = require('express');
     const bodyParser = require('body-parser');
    
     const app = express();
     const port = 3000;
    
     app.use(bodyParser.json());
    
     // Sample tasks array (for demonstration purposes)
     let tasks = [
       { id: 1, title: 'Task 1', description: 'Description for Task 1' },
       { id: 2, title: 'Task 2', description: 'Description for Task 2' },
     ];
    
     // Get all tasks
     app.get('/tasks', (req, res) => {
       res.json(tasks);
     });
    
     // Get a specific task by ID
     app.get('/tasks/:id', (req, res) => {
       const taskId = parseInt(req.params.id);
       const task = tasks.find((t) => t.id === taskId);
    
       if (task) {
         res.json(task);
       } else {
         res.status(404).json({ error: 'Task not found' });
       }
     });
    
     // Create a new task
     app.post('/tasks', (req, res) => {
       const newTask = req.body;
       newTask.id = tasks.length + 1;
       tasks.push(newTask);
       res.status(201).json(newTask);
     });
    
     // Update an existing task
     app.put('/tasks/:id', (req, res) => {
       const taskId = parseInt(req.params.id);
       const updatedTask = req.body;
    
       tasks = tasks.map((task) =>
         task.id === taskId ? { ...task, ...updatedTask } : task
       );
    
       res.json(updatedTask);
     });
    
     // Delete a task by ID
     app.delete('/tasks/:id', (req, res) => {
       const taskId = parseInt(req.params.id);
       tasks = tasks.filter((task) => task.id !== taskId);
       res.json({ message: 'Task deleted successfully' });
     });
    
     app.listen(port, () => {
       console.log(`Server is running on port ${port}`);
     });
    
  3. Run the Server: Start the server by running:

     node server.js
    
  4. Test the API: You can use tools like curl, Postman, or even JavaScript code (in a browser or Node.js script) to interact with your API. For example:

  5. Integrate with JavaScript (Client-Side):In a web app, you can use JavaScript to send HTTP requests to your API. You can use the fetch API or a library like Axios to make it easier.

     // Example using fetch
     fetch('http://localhost:3000/tasks')
       .then((response) => response.json())
       .then((data) => console.log(data))
       .catch((error) => console.error(error));
    

This is a simple example to begin with. In real situations, you might need features like authentication, connecting to a database, handling errors, and more. Also, you can think about using modern frameworks like Express.js, Nest.js, or other tools to create more advanced and scalable APIs.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!