Phone: +91 - 7503630654 Email: warriorsitech@gmail.com
Node.js simplifies API development, offering a robust platform for creating RESTful APIs.
Understanding RESTful APIs:
Setting Up Node.js for API Development:
Creating a Simple RESTful API Example:
javascript// Import required modulesconst express = require('express');const app = express();const PORT = 3000;// Sample data (in-memory database for demonstration)let data = [{ id: 1, name: 'Example 1' },{ id: 2, name: 'Example 2' }];// Endpoint for fetching all dataapp.get('/api/data', (req, res) => {res.json(data);});// Endpoint for fetching a specific item by IDapp.get('/api/data/:id', (req, res) => {const id = parseInt(req.params.id);const item = data.find(item => item.id === id);if (item) {res.json(item);} else {res.status(404).send('Item not found');}});// Listen on specified portapp.listen(PORT, () => {console.log(`Server running on port ${PORT}`);});
Explanation of the Example:
Conclusion: Node.js, paired with Express.js, offers a straightforward approach to creating RESTful APIs. This example illustrates the simplicity of setting up basic endpoints for data retrieval.
Embarking on API development with Node.js opens doors to efficient communication between software systems. Experiment, expand, and dive deeper into creating robust APIs to meet diverse needs.
Leave a comment