If you’ve ever used a mobile app that fetches weather data, sends messages, or displays your profile info – you’ve already interacted with a REST API. But what exactly is a REST API, and how can you build one yourself using Node.js and Express? In this article, I’ll walk you through everything from scratch – no fluff, no jargon. Just practical knowledge and working code. Ready? Let’s dive in!
What is a REST API (in simple words)?
A REST API (or RESTful API) is like a waiter at a restaurant. You (the client) tell the waiter what you want (like “Get me user data”), and the waiter (API) brings it back from the kitchen (database/server).
You use different HTTP methods to interact:
- GET – Read data
- POST – Create new data
- PUT – Update existing data
- DELETE – Remove data
Now let’s build one from scratch using Node.js and Express!
What You’ll Need
- Node.js installed (https://nodejs.org)
- Any code editor (like VS Code)
- Terminal access
Step 1: Set Up Your Project
Open your terminal and run:
Now create a file named server.js
.
Step 2: Create a Basic Express Server
Inside server.js
, add this code:
Open your browser and visit http://localhost:3000
. You should see:
Hello, API world!
Step 3: Create a Simple Data Store
Let’s simulate a mini database using an array:
Step 4: Add Routes (CRUD)
1.GET all users