create a crud api in express in javascript

To create a CRUD API in Express.js, you need to follow the following steps:

  1. Install Express.js and other dependencies such as Mongoose, which is a library that helps to connect and interact with MongoDB.
index.tsx
npm install express mongoose body-parser --save
48 chars
2 lines
  1. Set up the server and create endpoints for performing CRUD operations. Below is an example of how to create a RESTful API with Express.js:
index.tsx
//import the required dependencies
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

//create the express app
const app = express();

//configure the app to use body-parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//connect to the database
mongoose.connect(<db-url>, () => console.log('connected to database'));

//define the schema for the database
const UserSchema = mongoose.Schema({
    name: String,
    email: String,
    age: Number
});

//create the model for the schema
const User = mongoose.model('User', UserSchema);

//define the routes for the API
app.get('/user', (req, res) => {
    //retrieve all users from the database
    User.find((err, users) => {
        if (err) return res.status(500).json({ error: err });
        res.json(users);
    });
});

app.post('/user', (req, res) => {
    //create a new user in the database
    const user = new User(req.body);
    user.save((err) => {
        if (err) return res.status(500).json({ error: err });
        res.json({ message: 'User created successfully' });
    });
});

app.put('/user/:id', (req, res) => {
    //update an existing user in the database
    User.findByIdAndUpdate(req.params.id, req.body, (err) => {
        if (err) return res.status(500).json({ error: err });
        res.json({ message: 'User updated successfully' });
    });
});

app.delete('/user/:id', (req, res) => {
    //delete an existing user from the database
    User.findByIdAndRemove(req.params.id, (err) => {
        if (err) return res.status(500).json({ error: err });
        res.json({ message: 'User deleted successfully' });
    });
});

//start the server
app.listen(3000, () => console.log('server started'));
1779 chars
62 lines
  1. Test the API using a tool such as Postman to send GET, POST, PUT and DELETE requests to the server and see the results in the response.

This is a basic example of how to create a CRUD API in Express.js with MongoDB. You can customize this code to create APIs for any type of data you want.

gistlibby LogSnag