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

Scale globally with MongoDB Atlas. Try free.

Scale globally with MongoDB Atlas. Try free.

MongoDB Atlas is the global, multi-cloud database for modern apps trusted by developers and enterprises to build, scale, and run cutting-edge applications, with automated scaling, built-in security, and 125+ cloud regions.

Learn More

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarklyโ€™s MCP server ๐Ÿ

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

๐Ÿ‘‹ Kindness is contagious

Delve into this thought-provoking piece, celebrated by the DEV Community. Coders from every walk are invited to share their insights and strengthen our collective intelligence.

A heartfelt โ€œthank youโ€ can transform someoneโ€™s dayโ€”leave yours in the comments!

On DEV, knowledge sharing paves our journey and forges strong connections. Found this helpful? A simple thanks to the author means so much.

Get Started