Express Rest API Simple CRUD using SQLite

mayank30

Mayank

Posted on March 18, 2023

Express Rest API Simple CRUD using SQLite

Node.js is a runtime environment that allows JavaScript to be used on the server-side. It is built on the V8 JavaScript engine from Google Chrome and provides a number of features and APIs that make it easy to develop server-side applications with JavaScript. Node.js is designed to be highly scalable and efficient, making it popular for building real-time web applications and other network applications.

Express.js, on the other hand, is a popular web framework for Node.js that provides a set of features and tools for building web applications and APIs. It is built on top of Node.js and provides a simple and flexible way to handle HTTP requests, route URLs, and process data. Express.js is highly customizable and allows developers to build a wide range of web applications, from small, simple websites to large, complex web applications.

In short, Node.js provides the runtime environment for executing JavaScript code on the server-side, while Express.js provides the framework for building web applications and APIs using Node.js. Together, they provide a powerful and flexible platform for developing server-side applications with JavaScript.

Getting Started

To create a new Express.js project, you can follow these steps:

Make sure you have Node.js installed on your machine. You can download it from the official website: https://nodejs.org/

Open your terminal or command prompt and create a new directory for your project:

mkdir my-express-project
Enter fullscreen mode Exit fullscreen mode

Navigate to the newly created directory:

cd my-express-project
Enter fullscreen mode Exit fullscreen mode

Initialize a new Node.js project using the following command:

npm init
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file in your project directory.

Install the express package using the following command:

npm install express
Enter fullscreen mode Exit fullscreen mode

This will download and install the express package and add it to your project's package.json file as a dependency.

Create a new file called app.js or index.js in your project directory and open it in your text editor.

In the app.js or index.js file, add the following code:

const express = require('express');
const app = express();
const port = 3000;

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

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

This sets up a simple Express.js server that listens on port 3000 and responds to requests to the root URL (/) with the message "Hello World!".

Start the server by running the following command in your terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

You should see a message in the terminal indicating that the server is listening on port 3000.

Open your web browser and go to http://localhost:3000. You should see the message "Hello World!" displayed in your browser.
Congratulations! You have now created a simple Express.js project.

Now Let's create API's

Let's install sequalize and sqlite package

SQLite is a free, open-source, lightweight, and self-contained database management system that is used for storing and managing data in a relational database. Unlike other traditional database management systems like MySQL, Oracle, or PostgreSQL, SQLite is a server-less database that is embedded in the application that uses it, making it very easy to use and deploy.

SQLite stores data in a single file, making it a great choice for small to medium-sized applications that do not require a large amount of data storage or a high level of concurrency. It is also cross-platform and runs on various operating systems like Windows, Linux, macOS, and many more.

SQLite supports SQL, which is a standard language for managing relational databases, and provides many features, such as ACID transactions, indexes, triggers, and views, that are commonly found in other database management systems. SQLite is widely used in many applications, including desktop software, mobile applications, web applications, and embedded systems.

npm install sequelize sqlite3
Enter fullscreen mode Exit fullscreen mode

Simple user table name, email and password to perform create user, get all users, edit user, delete user.

const express = require('express');
const bodyParser = require('body-parser');
const { Sequelize, Model, DataTypes } = require('sequelize');

const app = express();
const port = 3000;

// Create Sequelize instance
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: './database.sqlite'
});

// Define User model
class User extends Model {}
User.init({
  name: DataTypes.STRING,
  email: DataTypes.STRING,
  password: DataTypes.STRING
}, { sequelize, modelName: 'user' });

// Sync models with database
sequelize.sync();

// Middleware for parsing request body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// CRUD routes for User model
app.get('/users', async (req, res) => {
  const users = await User.findAll();
  res.json(users);
});

app.get('/users/:id', async (req, res) => {
  const user = await User.findByPk(req.params.id);
  res.json(user);
});

app.post('/users', async (req, res) => {
  const user = await User.create(req.body);
  res.json(user);
});

app.put('/users/:id', async (req, res) => {
  const user = await User.findByPk(req.params.id);
  if (user) {
    await user.update(req.body);
    res.json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

app.delete('/users/:id', async (req, res) => {
  const user = await User.findByPk(req.params.id);
  if (user) {
    await user.destroy();
    res.json({ message: 'User deleted' });
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Start server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Enter fullscreen mode Exit fullscreen mode

Congratulation !! 🎉
API's are ready to consume on front end.

If you like it

You can buy me coffee
https://www.buymeacoffee.com/mayankjhawar

Support me at Patreon
https://patreon.com/mayank120

💖 💪 🙅 🚩
mayank30
Mayank

Posted on March 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related