DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

πŸš€ Building a Simple REST API with Node.js & Express – A Step-by-Step Guide

APIs are the backbone of contemporary online applications, providing smooth communication between the frontend and backend.

In this post, we'll step through constructing a basic REST API using Node.js & Express from scratch. Let’s get started! πŸš€

πŸ“Œ Step 1: Setup Your Node.js Project

First, verify you have Node.js installed. Then, initialize a new project:

sh Copy Edit mkdir simple-api && cd simple-api npm init -y

This produces a package.json file, which maintains dependencies.

πŸ“Œ Step 2: Install Express.js

Express is a lightweight and quick framework for creating web applications in Node.js. Install it:

sh Copy Edit npm install express πŸ“Œ Step 3: Create Your Server

Create a new file server.js and add this code:

javascript Copy Edit const express = require('express'); const app = express(); const PORT = 3000;

app.get('/', (req, res) => { res.send('Hello, API! πŸš€'); });

app.listen(PORT, () => { console.log(Server is operating on http://localhost:${PORT}); });

What’s Happening?

βœ” express() initializes an Express app.

βœ” app.get('/') handles GET queries to the root URL.

βœ” app.listen(PORT) launches the server.

Run it with:

sh

Copy Edit node server. js

Visit http://localhost:3000 in your browserβ€”you should see "Hello, API! πŸš€".

πŸ“Œ Step 4: Add More Routes

Let’s build routes to handle CRUD actions (Create, Read, Update, Delete). Modify server. js:

javascript Copy Edit app.use(express.json()); // Middleware to parse JSON

const users = [{ id: 1, name: 'John Doe' }] ;

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

// Add a new user app. post('/users', (req, res) => { const newUser = { id: users.length + 1, ...req.body }; users.push(newUser); res.status(201).json(newUser); });

Now you can:

βœ” GET /users β†’ Retrieve all users

βœ” POST /users β†’ Add a new user

Test with Postman or cURL:

sh Copy Edit curl -X POST -H "Content-Type: application/json" -d '{"name": "Jane Doe"}' http://localhost:3000/users πŸ“Œ Step 5: Handling Errors

Let’s add error handling to enhance our API:

javascript Copy Edit app.use((req, res) => { res.status(404).json({ message: 'Route not found!' }); });

Now, if a user accesses an incorrect endpoint, they receive a 404 error instead of a blank answer.

πŸ“Œ Step 6: Running and Testing 1️⃣ Start the server:

sh Copy Edit node server. js

2️⃣ Open http://localhost:3000/users in your browser or Postman to test.

3️⃣ Use Postman to submit a POST request to /users.

πŸš€ Next Steps πŸ”Ή Add MongoDB with Mongoose for data storage. πŸ”Ή Implement JWT authentication for security. πŸ”Ή Deploy the API using Render, Vercel, or Heroku.

By following these instructions, you’ve constructed a completely functioning REST API using Node.js & Express! πŸŽ‰

πŸ’¬ Have questions? Drop them in the comments!

#NodeJS #ExpressJS #RESTAPI #Backend #WebDevelopment

Top comments (0)