Learn how to build RESTful APIs using Express.js and MongoDB, two powerful tools for modern web development.
# Building RESTful APIs with Express and MongoDB Express.js and MongoDB are powerful tools for building modern web applications. In this guide, we'll walk through the process of creating a RESTful API using these technologies. ## Setting Up Express First, install Express and other necessary packages: ```bash npm install express mongoose body-parser ``` Create an Express server: ```javascript const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', () => { console.log('Connected to MongoDB'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` ## Defining a Mongoose Model Create a Mongoose model for your data: ```javascript const Schema = mongoose.Schema; const ItemSchema = new Schema({ name: String, quantity: Number, price: Number, }); const Item = mongoose.model('Item', ItemSchema); ``` ## Creating RESTful Routes Define your API routes: ```javascript app.get('/items', async (req, res) => { try { const items = await Item.find(); res.json(items); } catch (err) { res.status(500).send(err); } }); app.post('/items', async (req, res) => { const newItem = new Item(req.body); try { const savedItem = await newItem.save(); res.status(201).json(savedItem); } catch (err) { res.status(400).send(err); } }); app.get('/items/:id', async (req, res) => { try { const item = await Item.findById(req.params.id); if (item) { res.json(item); } else { res.status(404).send('Item not found'); } } catch (err) { res.status(500).send(err); } }); app.put('/items/:id', async (req, res) => { try { const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true }); if (updatedItem) { res.json(updatedItem); } else { res.status(404).send('Item not found'); } } catch (err) { res.status(400).send(err); } }); app.delete('/items/:id', async (req, res) => { try { const deletedItem = await Item.findByIdAndDelete(req.params.id); if (deletedItem) { res.json(deletedItem); } else { res.status(404).send('Item not found'); } } catch (err) { res.status(500).send(err); } }); ``` With these steps, you've created a basic RESTful API using Express.js and MongoDB.
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. In this blog, we will explore how to build RESTful APIs using Express.js and MongoDB.