DEV Community

Cover image for NodeJS + Express part 4: CRUD API
Eric The Coder
Eric The Coder

Posted on

NodeJS + Express part 4: CRUD API

Here is a series of articles that will allow you to create backend applications with NodeJS + Express.

This series is the continuation of my series on the basics of NodeJS. If you don't have basic knowledge of NodeJS read this series first: Introduction to NodeJS

Node.js is today a must, so it is essential for a developer to master it.

So I will publish a new article about every two days and little by little you will learn everything there is to know about Node.js + Espress

To not miss anything follow me on twitter: https://twitter.com/EricTheCoder_


CRUD API

Now that we know the basics concept, it's time to build real CRUD API (create, read, update, delete)

We will build all those CRUD routes:

Create: POST /api/products

Read all: GET /api/products

Read: GET /api/product/1

Update: PUT /api/products/1

Delete: DELETE /api/products/1

Return status

With a CRUD API you can return data but also status code.

Here is a list of some status code and there meaning

res.status(200) // Ok
res.status(201) // Created
res.status(204) // No content
res.status(400) // Bad request
res.status(401) // Unauthorized
res.status(403) // Forbidden
res.status(404) // Not found
res.status(500) // Server error
Enter fullscreen mode Exit fullscreen mode

Create a file name data.js and copy/paste this code

const products = [
    { id: 1, name: 'iPhone', price: 800 },
    { id: 2, name: 'iPad', price: 650 },
    { id: 3, name: 'iWatch', price: 750 }
]

module.exports = products
Enter fullscreen mode Exit fullscreen mode

Load data and start the server

const express = require('express')
const app = express()
const products = require('./data.js')

app.listen(5000, () => {
    console.log('server is listening on port 5000')
})
Enter fullscreen mode Exit fullscreen mode

Create: POST /api/products

app.use(express.json()) // parse json body content

app.post('/api/products', (req, res) => {
    const newProduct = {
        id: products.length + 1,
        name: req.body.name,
        price: req.body.price
    }
    products.push(newProduct)
    res.status(201).json(newProduct)
})
Enter fullscreen mode Exit fullscreen mode

The app.use(express.json) is a middleware that take JSON content and create related req.body properties. (ex. req.body.name and req.body.price)

The res.status(201).json(newProduct) set the return response status to 201 (created) and also return the newProduct data in JSON format.

Read all: GET /api/products

app.get('/api/products', (req, res) => {
    res.json(products)
})
Enter fullscreen mode Exit fullscreen mode

Read: GET /api/product/1

app.get('/api/products/:productID', (req, res) => {
    const id = Number(req.params.productID)
    const product = products.find(product => product.id === id)

    if (!product) {
        return res.status(404).send('Product not found')
    }
    res.json(product)
})
Enter fullscreen mode Exit fullscreen mode

As seen in part 2, first we retrieved the productID from the route parameter.

Then we check if this product exist and send a response accordingly.

res.json(product) send the product in JSON format with a 200 ok status code.

Update: PUT /api/products/1

app.use(express.json()) // parse json body content

app.put('/api/products/:productID', (req, res) => {
    const id = Number(req.params.productID)
    const index = products.findIndex(product => product.id === id)
    if (index === -1) {
        return res.status(404).send('Product not found')
    }
    const updatedProduct = {
        id: products[index].id,
        name: req.body.name,
        price: req.body.price
    }
    products[index] = updatedProduct
    res.status(200).json('Product updated')
})
Enter fullscreen mode Exit fullscreen mode

Delete: DELETE /api/products/1

app.use(express.json()) // parse json body content

app.delete('/api/products/:productID', (req, res) => {
    const id = Number(req.params.productID)
    const index = products.findIndex(product => product.id === id)
        if (index === -1) {
        return res.status(404).send('Product not found')
    }
    products.splice(index,1)
    res.status(200).json('Product deleted')
})
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's all for today, follow me on twitter: https://twitter.com/EricTheCoder_ to be notified of the publication of the next article (within two days).

Top comments (4)

Collapse
 
ashlee380518 profile image
ashlee380518

This is great! Thank you.

Some small things to note:

Read: GET /api/product/1 <-- this is one of the headers and I copied and pasted it to add to the localhost url and it didn't work. I realized it was products not product. But just a small thing

Collapse
 
olsard profile image
olsard

Thanks, good explained.

Collapse
 
ibrahimsifat profile image
Ibrahim Sifat

thanks for sharing

Collapse
 
steve-lebleu profile image
Steve Lebleu

Thanks for sharing. There is a simple and good package to start with express and typescript :

GitHub logo konfer-be / typeplate

REST API boilerplate with Typescript, Express.js, Typeorm and Mocha.

Typescript / Express / Typeorm REST API boilerplate

Node TypeScript Express Typeorm Mocha

Build Coverage Status CodeFactor Grade Requires.io (branch) Snyk Vulnerabilities for GitHub Repo

MIT Licence

Ready to use RESTful API boilerplate builded with Express.js, Typescript TypeORM and Mocha. 🤘

Thanks to Daniel F. Sousa for inspiration with her Express ES2017 REST API boilerplate 🍺 🍺 🍺

> Features

  • Basics
    • Clear & clean code architecture with classic layers such controllers, services, repositories, models, ...
    • Object Relational Mapping with typeorm.
    • Entity generation with rsgen.
    • Business validation with self designed business members.
    • Logs management with morgan and winston.
    • Changelog completion with auto-changelog.
    • Testing with included unit and e2e test sets builded with mocha, chai, sinon and supertest.
    • Documentation with api-doc.
  • Security
    • SSL secure connection with native HTTPS node module.
    • Cross Origin Resource Sharing with CORS.
    • Securized HTTP headers with helmet.
    • HTTP header pollution preventing with hpp.
    • API request rate limit with express-rate-limit.
    • Route validation with joi.
    • HTTP friendly errors with boom and…