Table of Contents
Express.js is a popular web framework for Node.js that simplifies the process of building web applications and APIs. If you're new to Express.js, this tutorial will guide you through creating your first API endpoint step-by-step. By the end, you'll understand how to set up a basic server and handle HTTP requests.
Prerequisites
- Basic knowledge of JavaScript and Node.js
- Node.js installed on your computer
- Text editor (like VS Code)
- Command line interface
Step 1: Initialize Your Project
Open your terminal and create a new directory for your project. Navigate into it and initialize a new Node.js project:
mkdir express-api-tutorial
cd express-api-tutorial
npm init -y
Step 2: Install Express.js
Install Express.js using npm:
npm install express
Step 3: Create Your Server File
Create a new file named app.js in your project directory. This file will contain your server code.
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 4: Create Your First API Endpoint
Add a GET route to your app.js file that responds with a JSON message:
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello, World!' });
});
Step 5: Run Your Server
In your terminal, run the server using Node.js:
node app.js
Open your browser and go to http://localhost:3000/api/hello. You should see the JSON message:
{"message":"Hello, World!"}
Next Steps
Congratulations! You've created your first API endpoint with Express.js. Next, you can explore handling other HTTP methods, adding middleware, or connecting to databases to build more complex APIs.