# Creating a RESTful API with Node.js and Express

Today, we're going to explore how to create a RESTful API using Node.js and Express. By the end of this tutorial, you'll be able to set up a simple server and handle HTTP requests. Let's get started!

Before we dive in, ensure you have Node.js installed on your machine. If you don't, you can download it from the official Node.js website. Now, let's begin!

# Step 1: Setting Up Your Project

Firstly, let's create a new folder for our project and initialize it with npm (Node Package Manager).

mkdir node-express-api
cd node-express-api
npm init -y

The -y flag is used to automatically say yes to the prompts, creating a default package.json file.

# Step 2: Installing Express

Next, we'll install Express, which is a minimal web application framework for Node.js.

Copy code

npm install express

# Step 3: Creating Your Server

Now, let's create a new file named app.js and set up a simple server.

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

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

In this code, we import Express, create an instance of an Express application, and start the server on port 3000.

# Step 4: Defining Routes

Let's define a simple route to handle GET requests at the root of our API.

app.get('/', (req, res) => {
    res.send('Welcome to my Node.js and Express API!');
});

Now, if you start your server with node app.js and navigate to http://localhost:3000 (opens new window) in your web browser, you should see the message: "Welcome to my Node.js and Express API!"

# Step 5: Creating a RESTful Endpoint

Now, let's create a RESTful endpoint. For this example, we'll create a simple in-memory array of 'books' and a GET endpoint to retrieve them.

Copy code
let books = [
    { id: 1, title: 'Node.js for Beginners', author: 'Ingrid Svensson' },
    { id: 2, title: 'Mastering Express', author: 'Ingrid Svensson' }
];

app.get('/books', (req, res) => {
    res.json(books);
});

Now, if you navigate to http://localhost:3000/books (opens new window), you'll see the JSON representation of our books array.

That's it! You've just set up a simple server and handled HTTP GET requests using Node.js and Express. Remember, this is just the tip of the iceberg. You can create more complex routes, handle different HTTP methods, connect to a database, and much more with Node.js and Express.

I hope this tutorial has been helpful in getting you started with creating RESTful APIs using Node.js and Express. Keep experimenting and happy coding!