[text] restapi

Viewer

  1. const express=require("express");
  2. const app=express();
  3. const bodyparser=require("body-parser");
  4. app.use(bodyparser.json());
  5. const employees=[
  6.     {id:1,empname:"Sachin",dept:"CSE",address:"Hyd"},
  7.     {id:2,empname:"Karthik",dept:"CSE",address:"Warangal"},
  8.     {id:3,empname:"sandeep",dept:"ECE",address:"Vizag"},
  9.  
  10.  
  11. ];
  12. app.get("/api/employees",(req,res)=>{
  13.     res.json(employees);
  14. });
  15. app.get("/api/employees/:id",(req,res)=>{
  16.     const employee=employees.find(
  17.         (employee)=> employee.id==parseInt(req.params.id)
  18.     );
  19.     if(!employee){
  20.         res.json({message:'employee with ${req.params.id} does not exists'});
  21.     }
  22.     res.json(employee);
  23. });
  24. app.post("/api/employees",(req,res)=>{
  25.     const employee={
  26.         id:employees.length+1,
  27.         empname:req.body.empname,
  28.         dept:req.body.dept,
  29.         address:req.body.address,
  30.     };
  31.     employees.push(employee);
  32.     res.json(employee);
  33. });
  34. app.put("/api/employees/:id",(req,res)=>{
  35.     const employee=employees.find(
  36.         (employee)=>employee.id==parseInt(req.params.id)
  37.     );
  38.     if(!employee){
  39.         res.json({message:'employee with ${req.params.id} does not exists'});
  40.     }
  41.     else{
  42.         employee.empname=req.body.empname
  43.         employee.dept=req.body.dept
  44.         employee.address=req.body.address
  45.     }
  46.     res.json(employee);
  47. });
  48. app.delete("/api/employees/:id",(req,res)=>{
  49.     const employee=employees.find(
  50.         (employee)=>employee.id==parseInt(req.params.id)
  51.     );
  52.     if(!employee){
  53.         res.json({message:'employee with ${req.params.id} does not exists'});
  54.     }
  55.     var index=employees.indexOf(employees);
  56.     employees.splice(index,1);
  57.     res.json(employee);
  58. });
  59. app.listen(3002);

Editor

You can edit this paste and save as new:


File Description
  • restapi
  • Paste Code
  • 09 May-2024
  • 1.7 Kb
You can Share it: