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


Building RESTful services with Express

REST is "Representational State Transfer", big name but let me break it down for you in simple terms. Over internet when two systems need to interface with each other they need some form/language to communicate, REST is that medium which enables transferring of data between two remote systems. REST is based on HTTP protocol and hence supports all the HTTP verbs like GET, POST, PUT, DELETE, PATH etc. We also have SOAP (Simple Object Access Protocol ) & WSDL (Web Service Definition Language) web services which are still used in many places but they are old and creepy. SOAP is based on XML format and is slow whereas with REST get the freedom to use formats like text, XML or JSON. REST takes the advantage of HTTP protocol because of which it is more faster and with json format which is faster to parse and compact as compared to XML.

REST stands for REpresentational State Transfer and API stands for Application Program Interface. REST is a software architectural style that defines the set of rules to be used for creating web services. Web services that follow the REST architectural style are known as RESTful web services. It allows requesting systems to access and manipulate web resources by using a uniform and predefined set of rules. Interaction in REST-based systems happen through Internet’s Hypertext Transfer Protocol (HTTP).
A Restful system consists of a:
  • client who requests for the resources.
  • server who has the resources.

It is important to create REST API according to industry standards which results in ease of development and increase client adoption.

Rules of REST API:
 There are certain rules which should be kept in mind while creating REST API endpoints.
·     REST is based on the resource or noun instead of action or verb based. It means that a URI of a REST API should always end with a noun. Example: /api/customers is a good example, but /api?type=customers is a bad example of creating a REST API.
·    HTTP verbs are used to identify the action. Some of the HTTP verbs are – GET, PUT, POST, DELETE, UPDATE, PATCH.
·     A web application should be organized into resources like users and then uses HTTP verbs like – GET, PUT, POST, DELETE to modify those resources. And as a developer, it should be clear that what needs to be done just by looking at the endpoint and HTTP method used.

  URI
HTTP VERB
DESCRIPTION
api/customers
GET
Get all customers
api/customers
POST
Add a customer
api/customers/1
PUT
Update a customer with id = 1
api/customers/1
DELETE
Delete a customer with id = 1
api/customers/1
GET
Get a customer with id = 1

·   Always use plurals in URL to keep an API URI consistent throughout the application.
·   Send a proper HTTP code to indicate a success or error status.

Steps to create RESTful Services with Express

1. create a new Folder ExpressApp

2. npm init --y // initialize package.json       // --y  is flag to set all package.json fields to default

3. npm i express // install express

4. Create a file name index.js

//First load express module using Code
const express = require('express');
const app = express();

app.get('/',(req,res=> {
      res.send('hello world');
// Call back function is called route handler
});

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


5. Now we create an application having Basic CRUD Operations using RESTFul Services with Express having HTTP methods. 



HTTP Methods
app.get();
app.post();
app.put();
app.deletet();


Wednesday, April 1, 2020

PHP Error and Exception

PHP Error Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. It’s very simple in PHP to handle errors. PHP offers a number of ways to handle errors.
 We are going to look at three (3) commonly used methods;

  1. Die statements– the die function combines the echo and exit function in one. It is very useful when we want to output a message and stop the script execution when an error occurs.
  2. Custom error handlers – these are user-defined functions that are called whenever an error occurs.
  3. PHP error reporting – the error message depending on your PHP error reporting settings. This method is very useful in a development environment when you have no idea what caused the error. The information displayed can help you debug your application.

Error Handling Examples

Example-1:
Using die() function: While writing your PHP program you should check all possible error conditions before going ahead and take appropriate action when required. Try the following example without having test.txt file and with this file.

<?php
   if(!file_exists("/tmp/test.txt")) {
      die("File not found");
   }else {
      $file = fopen("/tmp/test.txt","r");
      print "Opend file sucessfully";
   }
   // Test of the code here.
?>

This way you can write efficient code. Using the above technique you can stop your program whenever it errors out and displays a more meaningful and user-friendly message.

Example-2:

<?php   
  $denominator = 0;   
  echo 2 / $denominator;   
?> 

Assuming you saved the file simple_error.php, open the URL 
http://localhost/ simple_error.php
You will get the following results


As you can see from the above results, it makes our application look unprofessional and can be annoying to the user.
We will modify the above code and write an error handler for the application

<?php  
 $denominator = 0;  
 if ($denominator != 0) {  
   echo 2 / $denominator;  
 } else {  
   echo "cannot divide by zero (0)";  
 }  
 ?>

Assuming you saved the above code as error_handling.php, open the URL  http://localhost/error_handling.php


Note: it’s a good security practice displaying a message like the one shown above instead of showing the message like “File not found”.

PHP Exception Handling

An exception is an unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.
PHP provides the following specialized keywords for this purpose.
·       try: It represents a block of code in which exception can arise.
·       catch: It represents a block of code that will be executed when a particular exception has been thrown.
·     throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t handle itself.
·     finally: It is used in place of catch block or after catch block basically, it is put for cleanup activity in PHP code.

Why Exception Handling in PHP?
Following are the main advantages of exception handling over error handling
·     Separation of error handling code from normal code: In traditional error handling code there is always if-else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable.
·     Grouping of error types: In PHP both basic types and objects can be thrown as an exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.

Exception handling in PHP: Following code explains the flow of normal try-catch block in PHP:

<?php
// PHP Program to illustrate normal
// try-catch block code

function demo($var) {
    echo " Before try block";
    try {
        echo "\n Inside try block";
             
        // If var is zero then only if will be executed
        if($var == 0)
        {
                 
            // If var is zero then only exception is thrown

            throw new Exception('Number is zero.');
                 
            // This line will never be executed
            echo "\n After throw (It will never be executed)";
        }
    }
         
    // Catch block will be executed only 
    // When Exception has been thrown by try block

    catch(Exception $e) {
            echo "\n Exception Caught", $e->getMessage();
        }
         
        // This line will be executed whether
        // Exception has been thrown or not 
        echo "\n After catch (will be always executed)";
}
 
// Exception will not be raised

demo(5);
 
// Exception will be raised here

demo(0);
?>

Output:

 Before try block
 Inside try block
 After catch (will be always executed)
 Before try block
 Inside try block
 Exception CaughtNumber is zero.

 After catch (will be always executed)



Defining Custom Exceptions

You can even define your own custom exception handlers to treat different types of exceptions in a different way. It allows you to use a separate catch block for each exception type.

You can define a custom exception by extending the Exception class, because Exception is the base class for all exceptions. The custom exception class inherits all the properties and methods from PHP's Exception class. You can also add your custom methods to the custom exception class. Let's check out the following example:
Example:

<?php
// Extending the Exception class
class EmptyEmailException extends Exception {}
class InvalidEmailException extends Exception {}

$email = "someuser@example..com";

try{
    // Throw exception if email is empty
    if($email == ""){
        throw new EmptyEmailException("<p>Please enter your E-mail address!</p>");
    }   
    // Throw exception if email is not valid
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {          
        throw new InvalidEmailException("<p><b>$email</b> is not a valid E-mail address!</p>");
    }   
    // Display success message if email is valid
    echo "<p>SUCCESS: Email validation successful.</p>";
} catch(EmptyEmailException $e){
    echo $e->getMessage();
} catch(InvalidEmailException $e){
    echo $e->getMessage();
}
?>
In the above example we've derived two new exception classes: EmptyEmailException, and InvalidEmailException from the Exception base class. Multiple catch blocks are used to display different error messages, depending on the type of exception generated.
Since these custom exception classes inherit the properties and methods from the Exception class, so we can use the Exception class methods like getMessage(), getLine(), getFile(), etc. to retrieve error information from the exception object.
Output: