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)