In this tutorial, we will be creating a RESTful API using Node.js and Express. An API, or Application Programming Interface, is a set of rules that allows one software application to interact with another. A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data.
By the end of this tutorial, you will be able to:
Prerequisites:
A basic understanding of Javascript and Node.js is necessary for this tutorial. Familiarity with HTTP methods such as GET, POST, PUT, DELETE is also helpful.
First, we need to set up an Express server. Create a new directory for your project and initialize it with npm:
mkdir myAPI
cd myAPI
npm init -y
Next, install express:
npm install express
Now, create an index.js
file and set up a basic server:
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Routes define the endpoints of your API. You can define a simple GET route as follows:
app.get('/', (req, res) => {
res.send('Hello World!');
});
CRUD stands for Create, Read, Update, Delete - the four basic operations you can perform on a resource. In this tutorial, we'll implement these operations on a simple in-memory array to simulate a database.
First, let's define our "database":
let db = [];
Now, let's implement our CRUD operations:
app.post('/items', (req, res) => {
const item = req.body;
db.push(item);
res.send('Item added to the database');
});
app.get('/items', (req, res) => {
res.json(db);
});
app.put('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = req.body;
db[id] = item;
res.send(`Item at index ${id} has been updated`);
});
app.delete('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
db.splice(id, 1);
res.send(`Item at index ${id} has been removed`);
});
In this tutorial, we've set up an Express server, defined routes for our API, and implemented CRUD operations. As a next step, you could try connecting your API to a real database, such as MongoDB or PostgreSQL.
Remember, practice is key in programming. Keep building, keep iterating, and don't be afraid to make mistakes.