Create Your First Node.js REST API: A Step-by-Step Tutorial

Building your first REST API with Node.js is an essential skill for modern web development. In this comprehensive guide, we’ll create a fully functional API from scratch, perfect for beginners looking to expand their backend development skills.

Before we dive in, make sure you have Node.js installed on your system. If you haven’t installed Node.js yet, check out our guide on ‘node’ is not recognized as an internal or external command VSCode.

Setting Up Your Development Environment

First, let’s set up our development environment with the right tools. We’ll be using VS Code as our editor – if you haven’t installed it yet, follow our guide on Install VS Code on Ubuntu.

Project Initialization

// Create a new directory for your project
mkdir my-first-api
cd my-first-api
// Initialize npm project
npm init -yCode language: JavaScript (javascript)

Installing Required Dependencies

We’ll need Express.js for our API framework. Install it using npm:

npm install express
npm install nodemon --save-dev

Creating Your First Route

Let’s create a basic server with Express:

// index.js
const express = require('express');
const app = express();
// Middleware for parsing JSON bodies
app.use(express.json());
// Basic route
app.get('/api', (req, res) => {
    res.json({
        message: 'Welcome to your first API!'
    });
});
// Start server
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});Code language: PHP (php)

Implementing CRUD Operations

Let’s create a simple API for managing a list of items:

// Memory storage for our items
let items = [];
// GET all items
app.get('/api/items', (req, res) => {
    res.json(items);
});
// POST new item
app.post('/api/items', (req, res) => {
    const item = {
        id: items.length + 1,
        name: req.body.name
    };
    items.push(item);
    res.status(201).json(item);
});
// GET single item
app.get('/api/items/:id', (req, res) => {
    const item = items.find(i => i.id === parseInt(req.params.id));
    if (!item) return res.status(404).json({ message: 'Item not found' });
    res.json(item);
});Code language: JavaScript (javascript)

Testing Your API

To test your API endpoints, you can use tools like Postman or curl. Here are some example requests:

// Create new item
POST http://localhost:3000/api/items
Content-Type: application/json
{
    "name": "Test Item"
}
// Get all items
GET http://localhost:3000/api/itemsCode language: JavaScript (javascript)

Automating Server Restart

To make development easier, we’ll use nodemon to automatically restart our server when changes are made. For detailed instructions, check out our guide on Automate Node Server Restart with Nodemon.

Error Handling

Let’s add basic error handling:

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        message: 'Something went wrong!'
    });
});Code language: JavaScript (javascript)

Conclusion

Congratulations! You’ve created your first REST API with Node.js. This is just the beginning – you can expand this API by adding authentication, database integration, and more advanced features. If you’re interested in securing your API, check out our guide on A Comprehensive Guide to Web Security: Understanding HTTP Headers.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap