Harjutus 1: REST API demo käima saamine

REST API demo

Avame uus projekt ja terminal

Sisestame:
npm install express cors
Kirjutame appi kood:
// Loome moodulid
const express = require('express');
const cors = require('cors');

// Loome leht
const app = express();

app.use(cors());
app.use(express.json());

const widgets = [
    { id: 1, name: "Vlad", age: "18"},
    { id: 2, name: "Kesha", age: "17"},
    { id: 3, name: "Misha", age: "21"}
]

app.get('/widgets', (req, res) => {
    res.send(widgets);
})

app.get('/widgets/:id', (req, res) => {
    if (typeof widgets[req.params.id - 1] == 'undefined') {
        return res.status(404).send({ error: 'Widget not found'})
    }
    res.send(widgets[req.params.id - 1])
})

app.post('/widgets', (req, res) => {
    if (!req.body.name || !req.body.age) {
        return res.status(400).send({ error: "One or all params are missing"})
    }
    let neWidget = {
        id: widgets.length +1,
        name: req.body.name,
        age: req.body.age
    }
    widgets.push(neWidget)
    res.status(201)
        .location('localhost:8080/widgets/' + (widgets.length - 1))
        .send(neWidget)
})

// Kustutamine
app.delete('/widgets/:id', (req, res) => {
    const id = parseInt(req.params.id, 10);
    const index = widgets.findIndex(widget => widget.id === id);

    if (index === -1) {
        return res.status(404).send({ error: 'Widget not found' });
    }

    widgets.splice(index, 1);

    res.status(200).send({ message: 'Widget deleted successfully' });
});

app.listen(8080, () => {
    console.log('API up at: http://localhost:8080')
})

Käivitame:
node index.js

Kasutame Postman päringute saatmiseks ja endpointi testimiseks

Sisestame mu appi aadress:

http://localhost:8080/widgets

Kontrollime endpoint’id

GET /widgets

GET /widgets/id

POST /widgets

DELETE /widgets/id

Scroll to Top