Step-by-Step Guide to Creating a RESTful API with Node.js

Step-by-Step Guide to Creating a RESTful API with Node.js

1. Getting Started with Node.js and Express.js

💡 First in the Series: How to set up a basic Node.js server using Express.js.

  • What You'll Learn:

    • Setting up a Node.js project.

    • Installing and using Express.js.

    • Writing a basic server that listens to HTTP requests.

Setting up your first Express.js server might sound daunting, but with this step-by-step guide, you’ll have a running server in no time. This tutorial is perfect for beginners, and we’ll cover everything from initializing your project to connecting your server. Let’s get started! 🎉


Step 1: Create a Folder

Start by creating a folder for your project.
👉 Folder Name: REST_API (You can name it anything you like.)


Step 2: Open Your Folder in VS Code

  1. Open Visual Studio Code.

  2. Navigate to File > Open Folder and select the folder you just created.

  3. Open the integrated terminal by clicking Terminal > New Terminal in VS Code.


Step 3: Initialize a Node.js Project

Run the following command in the terminal to create a new package.json file:

npm init -y

✅ This file will manage your project's dependencies and metadata.


Step 4: Install Required Packages

Now, install Express (our framework) and Nodemon (for auto-reloading the server during development).

  1. Install Express:

     npm install express
    
  2. Install Nodemon globally for automatic refresh:

     npm install -g nodemon
    

Step 5: Create the app.js File

Inside your folder, create a new file called app.js.
This file is where you’ll write the code to set up and run your server.


Step 6: Write Your Express.js Server Code

Below is the code you’ll write in app.js, explained line by line:

// 1. Import the Express library to create a server and handle HTTP requests
const express = require('express');

// 2. Create an instance of Express to use its features
const app = express();

// 3. Set the port for the server
// Use the environment variable PORT if available; otherwise, default to 3000
const PORT = process.env.PORT || 3000;

// 4. Define a GET route for the root URL ('/')
// When this route is accessed, send "Hello World" as the response
app.get('/', (req, res) => {
    res.send('Hello World'); // Response sent to the client
});

// 5. Define an asynchronous function to start the server
const start = async () => {
    try {
        // Start the server and listen on the specified port
        app.listen(PORT, () => {
            console.log(`${PORT} yes I am connected`); // Logs a success message
        });
    } catch (error) {
        console.log(error); // Logs any errors that occur
    }
};

// 6. Call the `start` function to initialize the server
start();

Step 7: Run the Server

Update Your package.json

Modify the scripts section in your package.json file to include the following:

"scripts": {
  "start": "node app.js",
  "dev": "nodemon app.js"
}

Here’s what each script does:

  • start: Runs the app.js file using Node.js. Use this for production.

  • dev: Uses nodemon to automatically restart your server whenever you make changes during development.

To start your server, use Nodemon so the server automatically reloads when you save changes.

  1. Run the following command in the terminal:

     npm run dev
    
  2. Open your browser and visit:
    👉 http://localhost:3000

    You should see "Hello World" displayed on your screen! 🎉


Congratulations! 🎉

You’ve successfully created your first Express.js server.


Key Points to Remember

  1. Nodemon: It saves time during development by automatically restarting the server when changes are detected.

  2. Port Configuration: Always check that your port is available. Use environment variables for flexibility.

  3. Asynchronous Functions: Using async makes your code scalable for future enhancements.


💡 Next in the Series: How to create endpoints in Express.js for RESTful API development.

  • What You'll Learn:

    • Understanding RESTful principles.

    • Defining CRUD (Create, Read, Update, Delete) operations.

    • Writing API endpoints with Express.js.

Did you find this article valuable?

Support YASH BLOGS by becoming a sponsor. Any amount is appreciated!