In this section, we will walk through the process of creating a basic server for a RESTful API. We will use Node.js and Express.js, a popular framework for building web applications and APIs with Node.js. By the end of this section, you will have a simple server up and running that can handle basic HTTP requests.

Prerequisites

Before we start, ensure you have the following installed on your machine:

  • Node.js (v12 or higher)
  • npm (Node Package Manager)

You can download and install Node.js and npm from nodejs.org.

Step-by-Step Guide

  1. Setting Up the Project

  1. Create a Project Directory: Open your terminal and create a new directory for your project. Navigate into the directory.

    mkdir basic-rest-api
    cd basic-rest-api
    
  2. Initialize a Node.js Project: Initialize a new Node.js project by running the following command and following the prompts.

    npm init -y
    

    This will create a package.json file in your project directory.

  3. Install Express.js: Install Express.js using npm.

    npm install express
    

  1. Creating the Server

  1. Create the Server File: Create a new file named server.js in your project directory.

    touch server.js
    
  2. Write the Basic Server Code: Open server.js in your preferred code editor and add the following code:

    const express = require('express');
    const app = express();
    const port = 3000;
    
    // Basic route
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    // Start the server
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
    

  1. Running the Server

  1. Start the Server: In your terminal, run the following command to start the server.

    node server.js
    
  2. Access the Server: Open your web browser and navigate to http://localhost:3000. You should see the message "Hello World!".

  1. Handling Different HTTP Methods

Let's extend our server to handle different HTTP methods (GET, POST, PUT, DELETE).

  1. Add Routes for Different Methods: Update server.js to include routes for different HTTP methods.
    const express = require('express');
    const app = express();
    const port = 3000;
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    // Basic GET route
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    // GET route
    app.get('/api/resource', (req, res) => {
      res.json({ message: 'GET request received' });
    });
    
    // POST route
    app.post('/api/resource', (req, res) => {
      const data = req.body;
      res.json({ message: 'POST request received', data });
    });
    
    // PUT route
    app.put('/api/resource/:id', (req, res) => {
      const { id } = req.params;
      const data = req.body;
      res.json({ message: `PUT request received for ID: ${id}`, data });
    });
    
    // DELETE route
    app.delete('/api/resource/:id', (req, res) => {
      const { id } = req.params;
      res.json({ message: `DELETE request received for ID: ${id}` });
    });
    
    // Start the server
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
    

  1. Testing the Server

You can use tools like Postman or curl to test the different routes.

Example Requests:

  • GET Request:

    curl http://localhost:3000/api/resource
    
  • POST Request:

    curl -X POST http://localhost:3000/api/resource -H "Content-Type: application/json" -d '{"name": "John Doe"}'
    
  • PUT Request:

    curl -X PUT http://localhost:3000/api/resource/1 -H "Content-Type: application/json" -d '{"name": "Jane Doe"}'
    
  • DELETE Request:

    curl -X DELETE http://localhost:3000/api/resource/1
    

Summary

In this section, we have:

  • Set up a basic Node.js project.
  • Installed and used Express.js to create a simple server.
  • Created routes to handle different HTTP methods (GET, POST, PUT, DELETE).
  • Tested the server using curl commands.

This basic server setup forms the foundation for building more complex RESTful APIs. In the next sections, we will dive deeper into handling requests and responses, authentication, error handling, and more.

© Copyright 2024. All rights reserved