create a rest api in javascript

To create a REST API in JavaScript using Node.js and Express:

  1. Install Node.js and Express by running the following command in your terminal:
npm install --save express
27 chars
2 lines
  1. Create a new file, server.js, and require the necessary modules:
index.tsx
const express = require('express');
const app = express();
59 chars
3 lines
  1. Define your API routes:
index.tsx
app.get('/api/users', (req, res) => {
  // get all users logic
});

app.get('/api/users/:id', (req, res) => {
  // get user by id logic
});

app.post('/api/users', (req, res) => {
  // create new user logic
});

app.put('/api/users/:id', (req, res) => {
  // update user by id logic
});

app.delete('/api/users/:id', (req, res) => {
  // delete user by id logic
});
366 chars
20 lines
  1. Start the server:
index.tsx
app.listen(3000, () => {
  console.log('Server started on port 3000.');
});
76 chars
4 lines
  1. Run the application by running node server.js in your terminal.

Your REST API is now up and running, and can be accessed using the defined routes.

gistlibby LogSnag