Getting Started with Node.js and Express: Building a Simple RESTful API
Learn how to create a basic RESTful API using Node.js and Express, a popular JavaScript framework for building web applications.
Introduction to Node.js and Express
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows developers to create scalable and high-performance server-side applications. Express is a popular Node.js framework for building web applications and APIs.
Step 1: Install Node.js and Express
To start, you need to have Node.js installed on your machine. You can download the latest version from the official Node.js website. Once installed, open your terminal and run the following command to create a new Node.js project:
mkdir my-api
npm init -y
cd my-api
npm install express
Step 2: Create a Simple RESTful API
Create a new file called app.js and add the following code to it:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
Step 3: Run the Application
Run the application using the following command:
node app.js
Open your web browser and navigate to http://localhost:3000 to see the 'Hello World!' message.
Step 4: Add More Routes
Let's add a few more routes to our API. Update the app.js file with the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/users', (req, res) => {
res.json([{ name: 'John Doe', age: 30 }, { name: 'Jane Doe', age: 25 }]);
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
Now, when you navigate to http://localhost:3000/users, you should see a JSON response with a list of users.
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based Node.js video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked Node.js books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.