Monday, April 13, 2020

RESTful API with GET and POST Request


Index.js: Update code in the Index.js for GET Request: 

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

const courses = [
  { id: 1name: 'course1' },
  { id: 2name: 'course2' },
  { id: 3name: 'course3' },
];
app.get('/', (reqres=> {
  res.send(
    '<h3 style="color:orange">Basic CRUD Operations using RESTful Services with ExpressJS</h3>'
  );
});

app.get('/api/courses', (reqres=> {
  res.send(courses);
});

app.get('/api/courses/:id', (reqres=> {
  const course = courses.find((c=> c.id === parseInt(req.params.id));
  if (!courseres.status(404).send('Course with given id not found ');
  res.send(course);
});

// Setting Environment Variable PORT
const port = process.env.PORT || 3000;
// Setting port on command line using set command
// SET PORT=5000

app.listen(port, () => {
  //    console.log('Server is Running on port 3000');
  //    console.log('Server is Running on port %s', port);
  console.log(`Server is Running on port ${port}`);
});

Output: localhost:3000


Output: localhost:3000/api/courses


Output: localhost:3000/api/courses/1


Output: localhost:3000/api/courses/10 (the record is not exist)




2. Handling POST Request

Index.js: Update code in the Index.js for POST Request: 

app.use(express.json());
// we are creating Middleware and for app.use() is use

app.post('/api/courses', (reqres=> {
  const course = {
    id: courses.length + 1,
    name: req.body.name
   //parsing json object and for this we must use app.use(express.json());
  };
  courses.push(course);
  res.send(course);
});

In order to Handle POST request, we need a tool called POSTMAN, which is a Google Chrome app for interacting with HTTP APIs. It presents you with a friendly GUI for constructing requests and reading responses.

To use POSTMAN we need to install Chrome Extension Postman


Now Open this extension from chrome's Application and select method as POST


Now select Body option on the bar and then select row from the next option bar and finally choose JSON as data type to be POST.
Now in the address bar, write the address as http://localhost:3000/api/courses
Add the data to be posted in the body area on the screen.


Now click on Send Button for POST request and see the output body of POSTMAN