Sunday, April 19, 2020

RESTful API with PUT and DELETE requests


3. Handling PUT Request
Index.js: Update code in the Index.js for PUT Request: 

// PUT Request
app.put('/api/courses/:id', (reqres=> {

  // look for the course (Copy the code of app.get('/api/courses'))
  // if not existing, return 404-resourse not found
  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);

  // validate (copy code from app.post('/api/courses'))
  // if invalid, return 400 - bad request
  const schema = {
    name: Joi.string().min(3).required(),
  };
  const result = Joi.validate(req.bodyschema);
  if (result.error) {
    res.status(400).send(result.error.details[0].message);
    return;
  }

  // update course
  // return update course to client
  course.name = req.body.name;
  res.send(course);
});

Output: To Execute PUT request, again we use POSTMAN tool with PUT request option.




4. Handling DELETE Request

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

// Delete Request
app.delete('/api/courses/:id', (reqres=> {
  // look for the course (Copy the code of app.get('/api/courses'))
  // if not existing, return 404-resourse not found
  const course = courses.find((c=> c.id === parseInt(req.params.id));
  if (!coursereturn res.status(404).send('Course with given id not found ');
  res.send(course);

  // delete course
  const index = courses.indexOf(course);
  courses.splice(index1);

  // return deleted course to client
  res.send(course);
});

Output: To Execute DELETE request, we use POSTMAN tool with DELETE request option


Saturday, April 18, 2020

Handling GET and POST Request

GET and POST are two common HTTP Request used for building REST API’s. Both of these calls are meant for some special purpose.
As per the documentation GET request are meant to fetch data from specified resource and POST are meant to submit data to a specified resource.

GET request:
Handling GET request in Express seems so easy. You have to create instance of express and call get method.

Login.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>Login Form</h2>
    <form action="/login.html" method="GET">
      Username <input type="text" name="uname" /><br /><br />
      Password <input type="password" name="pwd" /><br /><br />
      <input type="submit" value="LOGIN" />
    </form>
  </body>
</html>

GetReq.js
const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('Server is Running on 3000');
});

app.get('/', (reqres=> {
  res.sendFile(__dirname + '/login.html');
});
app.get('/login.html', (reqres=> {
  if (req.query.uname == 'admin' && req.query.pwd == '123') {
    res.send('Successful Login');
  } else {
    res.send('Invalid Login');
  }
});

// Fallback function
app.use(function (reqres) {
  res.write('No page here');
  res.end();
});

Output:

GET request can be cached and remains in browser history. This is why GET is not supposed to use for sensitive data (passwords, ATM pins, etc). GET are suppose to use to retrieve data only.

POST Request:

Express version 4 and above require extra middle-ware layer to handle a POST request. This middle-ware is called as ‘bodyParser’. 

Login.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>Login Form</h2>
    <form action="/login.html" method="POST">
      Username <input type="text" name="uname" /><br /><br />
      Password <input type="password" name="pwd" /><br /><br />
      <input type="submit" value="LOGIN" />
    </form>
  </body>
</html>

PostReq.js
const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('Server is Running on 3000');
});

//body-parser
const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

app.get('/', (reqres=> {
  res.sendFile(__dirname + '/login.html');
});
app.post('/login.html', (reqres=> {
  console.log(req.body);
if (req.body.uname == 'admin' && req.body.pwd == '123') {
  // to use request.body, you need to import body-parser package
    res.send('Successful Login');
  } else {
    res.send('Invalid Login');
  }
});

// Fallback function
app.use(function (reqres) {
  res.write('No page here');
  res.end();
});

Output:


Friday, April 17, 2020

Request and Response Objects

Express sends us two objects in this callback, which we called req and res, they represent the Request and the Response objects.
  • Request is the HTTP request. It gives us all the request information, including the request parameters, the headers, the body of the request, and more.
  • Response is the HTTP response object that we’ll send to the client.

Request Object in Express:
request.url           : URL of current object
request.method   : GET | POST
request.headers  : Used to read headers sent from browser to server
request.query      : Used to read query string parameters in the form of object [GET                                        request] Ex: {username:”abc”, password:”xyz”}
request.body       : Used to read query string parameters in the form of object [POST                                      request]. Ex: {username:”abc”, password:”xyz”}

Response Object in Express:
response.write()       : Passes string values to browser
response.end()         : Ends of the response
response.headers()  : Send response headers from server to browser
response.status()      : Used to set status code
response.sendFile()  : Used to read content of file and send the same response to browser
response.send()        : Used to read send string/object to browser
response.json()         : Used to read send json data to browser

Lets create an application that will describe Request and Response Objects:

 reqRes.js
const express = require('express');
const app = express();

app.get('/', (reqres=> {
  console.log(req.url);
  console.log(req.method);
  console.log(req.headers);
  console.log(req.query);
  console.log(req.body);

  res.header('content-type''text/html');
  res.status(500);
  res.write('This is a reply from server<br>');
  res.write('This is another reply from server');
  res.end();

  res.send('This is reply from server to browser using send()');
  // But you can send only one response using res.send()

  res.sendFile(__dirname + '/login.html');

  res.json([
    { id: 1name: "pankaj" },
    { id: 2name: "sachin" },
   ]);
});

app.listen(3000, () => {
  console.log('Server is Running on 3000');

});

Output : http://localhost:3000/?x=10&y=20

Request Objects 
Response Objects