0% found this document useful (0 votes)
4 views

notes-4

Chapter III covers server-side development using the Express framework, detailing its installation, application creation, and middleware usage. It explains how Express simplifies Node.js application development by allowing modular request handling and integration with template engines. The chapter also discusses routing, middleware functions, and testing Express applications, providing practical examples and code snippets for better understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

notes-4

Chapter III covers server-side development using the Express framework, detailing its installation, application creation, and middleware usage. It explains how Express simplifies Node.js application development by allowing modular request handling and integration with template engines. The chapter also discusses routing, middleware functions, and testing Express applications, providing practical examples and code snippets for better understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

CHAPTER III: SERVER-SIDE DEVELOPMENT WITH EXPRESS (E):

Topics covered:
Introduction to the Express Framework. Installing and Testing Express. Creating a Node.js Express App.
Restructuring an Express App. Creating Templates. Using Express Middleware Functions. Creating the
List Page. Creating the Details Page. Creating the Edit Page. Creating the Add Page. Deleting Data.
REST API Basics. Testing REST APIs. Refactoring APIs.

Q. Explain Express Framework in detail?


-------------------------------------------------------------------------------------------------------------
Introduction to Express.js
Node.js is a JavaScript run time environment which is used to create server-side applications and tools.
Node.js is fast, portable, and written in JavaScript but it does not directly support common tasks such
as handling requests, serving files, and handling HTTP methods such as GET and POST. This is where
Node.js’s rich ecosystem comes to our aid.
Express.js (Express) is a light web framework which sits on top of Node.js and it adds
functionality like (middleware, routing, etc.) and simplicity to Node.js.
When creating a Node.js web application, we write a single JavaScript application which listens to
requests from the browser, based on the request, the function will send back some data or an HTML
web page.

A request handler is a JavaScript function which takes a request and sends an appropriate response.
Node.js APIs can get complex and writing how to handle a single request can end up being over 50 lines
of code. Express makes it easier to write Node.js web applications.
Advantages of using Express with Node.js
 Express lets you take away a lot of the complexities of Node.js while adding helpful functions to
a Node.js HTTP server.
 Instead of a large request handler function, Express allows us to handle requests by writing
many small modular and maintainable functions.
 Express is not opinionated, meaning Express does not enforce any “right way” of doing things.
You can use any compatible middleware, and you can structure the app as you wish, making it
flexible.
 We can integrate with a template rendering engine (also called a view rendering engine in some
articles) of our choice like Jade, Pug, EJS, etc.
A template engine enables you to use static template files and at runtime change the values of variables
in those files.
 You can set up “middleware” for request processing.
Basic Express Application
Let’s create a basic Express example app. To use Express, we first need to install it via npm using the
command below.
$ npm install express --save
Next, let’s write the code for our example app. Create a file called app.js.
//in app.js
var express = require("express");
var app = express();
//2
app.get("/", function(req, res){
res.send("HELLO WORLD");
});
//3
app.listen(3000, function(){
console.log("Application started and Listening on port 3000");
});
The code above creates a basic Express application. To run this script, go to your command prompt and
enter the command node app.js in the project directory.
In the console, we can see Application started and Listening on port 3000 and if we visit
http://localhost:3000/ we can see HELLO WORLD.
Let’s look at what the code above is doing.
The first line imports the express module. The second line creates an Express application by calling the
top-level express() function.
Our app variable (express application) has methods for handling requests and configuring how the
application behaves. We can create multiple apps this way, each with their own requests and responses.
Lets examine the code in section two. app.get() is a function, called route definition, which tells the
express app how to handle an HTTP GET request to our server.
This function takes two main parameters, the first is the route or path which is the relative path from
the root of the server; the second is a function that is invoked whenever there is a request to that path.
In this case, we are listening for GET requests to / which is the root of the website.
The second parameter, the callback function, has two arguments req and res. req represents
the request sent from the browser to the server. res represents the response that the server sends
back.
The code in section three starts a server on the port 3000. You can go to localhost:3000 to view your
response.
Core parts of
Express Middleware
Middleware is a set of functions that sit between a raw request and the final intended route. Middleware
functions have access to all the HTTP requests coming to the server. Middleware can handle tasks such
as logging, sending static files, authorization, and session management, etc.
In Node.js, the request and response objects are passed to one function (request handler) that we
write, in Express these objects are passed through a set of functions, called the middleware stack.
Express will start at the first function in the stack and execute in order down the stack.
Every function in the stack takes three arguments request, response and next. next is a function, that
when called Express executes the next function in the stack. This is a subtle difference between
middleware and a route handler which we saw above.
Let’s look at a basic static file server to understand middleware. Initialize a new npm project. Then
create a directory named static and copy-paste any available static files into the folder (text, images,
etc.).
Execute the following commands in the terminal. The touch command creates an empty file.
$ npm init -y
$ npm install express
$ mkdir static
$ touch static/dummy_file.txt
$ touch static/dummy_file2.txt
$ echo file1 > static/dummy_file.txt
$ echo file2 > static/dummy_file2.txt
$ touch app.js
Our app will have a logger function and a static file serving function.
//app.js
var express = require("express");
var path = require("path");
var fs = require("fs");
var app = express();
//1. Logging
app.use(function(req, res, next) {
console.log("Request IP: " + req.url);
console.log("Request date: " + new Date());
next();
});
//2. File Server
app.use(function(req, res, next) {
var filePath = path.join( dirname, "static", req.url);
fs.stat(filePath, function(err, fileInfo) {
if (err) {
next();
return;
}
if (fileInfo.isFile()) {
res.sendFile(filePath);
} else {
next();
}
});
});
app.listen(3000, function() {
console.log("App started on port 3000");
});
If we run this file using node app.js and go to localhost:3000/dummy_file.txt, we can see on the
screen file1.
If we go to the URL localhost:3000, we see an error Cannot GET / because we did not configure a route
handler for that path. Let’s look at the code.
The logger logs every request that comes into the server. app.use is used to define a middleware
function, it takes a function.
The next() function call tells Express to move onto the next function in the stack (remove the next() call
in your script, you will notice that it takes forever for the page to load, this is because the request gets
stuck on this middleware function).
We are using the path module to join the relative URL (from the request) and the directory name.
The fs module provides an API for interacting with the file system. We are checking if the file exists, if it
does not, we will go to next function in the stack if it does we will return that file using res.sendFile.
Using Third-Party Middleware
We can write our own middleware functions or import them similar to how we imported our modules in
Node.js using require.
Let’s use a popular open-source logger called morgan instead of writing our own logging function.
Install it using npm.
$ npm install morgan
We can call the use() on the Express app object to add the middleware to the stack.
var express = require("express");
var logger_morgan = require("morgan");
var app = express();
app.use(logger_morgan("short")); // logs short notation of requests
app.listen(3000);

Express comes with express.static middleware bundled with it, it can be used to serve static files
instead of the function in the previous section. It provides better security and performance than the
function we wrote.
JavaScript app.use(express.static("static"); //relative path
Any requested files in the directory “static” are served. localhost:3000/dummy_file.txt will show the
same result as above.
We can call static() multiple times to use multiple static asset directories. For example, consider we
have two directories static and public with static files and we wrote the following code:
JavaScript app.use(express.static("static"); app.use(express.static("public");
Suppose you make a request like localhost:3000/hello.html, Express looks up the files in the
static directory then public directory if the file exists then returns hello.html.
Routing
Express makes request handling easier by mapping requests to different request handlers. A request
handler is a function which handles all the requests to a specific path with a specific HTTP method.
In the basic example above, we saw how to handle a GET request. As an application grows in size the
routes grow as well as do the request handlers.
Lets see how we can use Routers to split a large app into smaller, maintainable functions.
According to the documentation, a Router is “an isolated instance of middleware and routes. Routers
can be thought of as “mini” applications only capable of performing middleware and routing”.
Routers can be used like middleware functions, they can be added to middleware stack using
the app.use() function. A simple example:
//app.js the main file

var express = require("express");


var apiRouter = require("./routes/api_router");
var app = express();
app.use("/api", apiRouter);
app.listen(3000);
Create a folder called routes and a file called api_router.js inside it.
//routes/api_router.js
var express = require("express");
var router = express.Router();
router.get("/route1", function(req, res, next){
res.send("Success !!");
next();
});
module.exports = router;
When you start the app and visit the URL localhost:3000/api/route1 you can see Success!!. Take a look
at all the router functions here.

Useful Routing Tips


Grabbing route
parameters
Suppose you are building a website for a company that showcases their products, each product has
a productID. You want the URL for product 1 to be /product/1.
Instead of defining a route for every product, you can define a single route for everything in the form
of product/productID and then return a file based on the productID. Here’s a rough example below that
you can modify for your use case.
var express = require("express");
var app = express();
// use a colon to grab a parameter
app.get("/product/:productId", function(req, res){
var pid = parseInt(req.params.productId, 10);
//Use res.send to manipulate string to get file with name as productID or something and use a static
file server
});
app.listen(3000);

Using Regular Expressions to match routes


Regular Expressions (RE) are patterns used to match character combinations in strings. We can use RE
to match parameters and define our routes.
For example, using the example above, if we wanted the productId to be only an integer we can try the
following:
var express = require("express")
app = express();
app.get(/^\/products\/(\d+)$/, function(req, res) {
var productId = parseInt(req.params[0], 10);
console.log("The user is asking for product"+productId);
//we can send a file related to request
var filename = "product" + productId + ".html"; // change this based on your setup
res.sendFile(filename);
});
app.listen(3000);
For the full example code, visit this gist.

Template Engines
Websites are built with HTML, you can dynamically generate HTML pages using Express. Dynamically
generated HTML pages are useful when you want to show real time data or change a page’s details
based on the user.
A template engine allows you to use static template files and at runtime replace variables in a template
file with actual data.
There are different template engines available like Pug, Jade, and EJS. Let’s see a basic template using
EJS.
First let’s install it using npm. Type npm install ejs and then create a directory called views to store your
templates and HTML files.
//app.js
var express = require("express");
var app = express();
app.set("view engine", "ejs"); //set view engine to ejs
app.set("views", "views"); //set views directory

app.get("/", function(req, res){ //res.render() renders a view and send the HTML to the client
res.render("index", {
message: "Hello and Welcome !!!" // this can be any thing you want
});
});
app.listen(3000);
Create a file called index.ejs in the views directory.
<html>
<head>
<meta charset="utf-8">
</head>

<body>
<%= message %>
</body>
</html>
If you go to the webpage you can see Hello and Welcome !!!. You can write JavaScript expressions
inside the <%= exp %>. Look at the docs for the complete syntax and rules.
Testing Express Applications.
Testing is an important part of developing software. Read this article where I discuss testing Node.js
applications using Mocha and Chai.
Q. Write a note on Installing and Testing Express?
-------------------------------------------------------------------------------------------------------------
Installing Express on Windows (WINDOWS 10)
Assuming that you have installed node.js on your system, the following steps should be followed to
install express on your Windows:
STEP-1: Creating a directory for our project and make that our working directory.
$ mkdir gfg
$ cd gfg
STEP-2: Using npm init command to create a package.json file for our project.
$ npm init
This command describes all the dependencies of our project. The file will be updated when adding
further dependencies during the development process, for example when you set up your build system.

Keep
pressing enter and enter “yes/no” accordingly at the terminus line.
STEP-3: Installing Express
Now in your gfg(name of your folder) folder type the following command line:
$ npm install express --save

NOTE- Here “WARN” indicates the fields that must be entered in STEP-2.
STEP-4: Verify that Express.js was installed on your Windows:
To check that express.js was installed on your system or not, you can run the following command line
on cmd:
C:\Users\Admin\gfg\node_modules>npm --version express
The version of express.js will be displayed on successful installation.

Q. How to create a Node.js Express Application?

Steps to create an Express.js Application


Express is the most popular minimalistic framework. It is built upon the built-in module HTTP of NodeJS
to facilitate the simple and easy interaction between frontend and backend logic through API, and also it
enables us to organize our business logic in so much pretty manner. It is much flexible and we can use
it for both the web and android. Also, it provides a very simple error handling procedure.
Approach: Below is the fundamental steps to write an express app. Here we are covering the topics
like setting up the environment with the installation of modules, creating an application, running the
web server, and performing basic communication with the server. Must-Know how to use the node
package manager for basic works, basic knowledge of the terminal for installing dependencies and
modules, basic knowledge of how a web application works, and a good knowledge of ES6.
Step by step Implementation:
Step 1: Write this command in your terminal, to create a nodejs application, because our
express server will work inside the node application.
Syntax:
npm init
This will ask you for few configurations about your project you can fill them accordingly, also you can
change it later from the package.json file.
Note: Use `npm init -y` for default initialization
Step 2: Install necessary dependencies for our application.
npm install express
Something like this will be shown on successful installation,

Step 3: The project structure will look like following.

Create a file app.js, for this article, we will write the whole express code in that file. This will be our
folder structure. Now Inside app.js, Import express with require keyword and create an app by calling
the express() function provided by the express framework. Set the port for our local application, 3000
is the default but you can choose any according to the availability of ports. Call the listen() function, It
requires path and callback as an argument. It starts listening to the connection on the specified path,
the default host is localhost, and our default path for the local machine is the localhost:3000, here
3000 is the port which we have set earlier. The callback function gets executed either on the successful
start of the server or due to an error.
 app.js

const express = require('express');

const app = express();


const PORT = 3000;

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: Now as we have created a server we can successfully start running it to
see it’s working, write this command in your terminal to start the express server.
node app.js
Output: You will see something like this on the terminal.

Now with all of this, we have created and run the server successfully, if your server is not starting then
there may be some error, try to analyze and read that error and resolve it accordingly.
Finally, after a successful run if you try to open the URL (localhost:3000) on the browser it will show
you cannot GET / because we have not configured any route on this application yet.
Step 4: Now we will set all the routes for our application.
Routes are the endpoints of the server, which are configured on our backend server and whenever
someone tries to access those endpoints they respond accordingly to their definition at the backend. If
you’re a beginner you can consider route as a function that gets called when someone requests the
special path associated with that function and return the expected value as a response. We can create
routes for HTTP methods like get, post, put, and so on.
Syntax: The basic syntax of these types of routes looks like this, the given function will execute when
the path and the request method resemble.
app.anyMethod(path, function)
Example 1: Setting up a basic get request route on the root URL (‘/’ path) of the server.
1. With app.get() we are configuring our first route, it requires two arguments first one is the path
and, the second one is a function that will be executed when anyone requests this path with GET
method. The express provides the request and response object as a parameter to all such types
of functions.
2. The req is a giant object which will be received from the user and res is an object which will be
sent to the user after the function finishes execution.
3. Later we are calling status() method it takes an HTTP status code as an argument and when the
response is returned, the status will be sent along.
4. Finally, we are returning the response to the user. The send() method takes a string, object,
array, or buffer as an argument and is used to send the data object back to the client as an HTTP
response, also there are lots of types of response in express like res.json() which is used to send
JSON object, res.sendFile() which is used to send a file, etc.
 app.js

const express = require('express');

const app = express();


const PORT = 3000;
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

app.get('/', (req, res)=>{


res.status(200);
res.send("Welcome to root URL of Server");
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: Save this code, restart the server, and open the localhost on the given
port. When client request with the appropriate method on the specified path ex: GET request on ‘/’
path, our function is returning the response as plain text If we open the network section in chrome
developers tools (press Ctrl+Shift+I to open) we will see the response returned by the localhost along
with all information.
Output:

Example 2: Setting up one more get request route on the ‘/hello’ path.
1. Most of the things are the same as the previous example.
2. The set() function is used to set HTTP header’s content type as HTML. When the browser
receives this response it will be interpreted as HTML instead of plain text.
3. Also in this example, we are not explicitly setting status, it is now concatenated with the
statement of sending the response. This is another way to send status along with a response.
 app.js

const express = require('express');

const app = express();


const PORT = 3000;

app.get('/hello', (req, res)=>{


res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello GFG Learner!</h1>");
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and App is
listening on port "+ PORT)

Page 10 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: Save this code, restart the server, and open the localhost on the given
port. Now access the ‘/hello’ route from the browser, The h1 text inside HTML will be shown as a
response.
Output:

Step 5: Now we will see how to send data to server.


Sometimes we have to send our data to the server for processing, for example when you try to log in
on Facebook you send a password and email to the server, Here we will see how to receive data from
the user request. We can send data with the request object on the specified path with appropriate HTTP
methods. Till now we were using the browser to interact with the server, but in this step, any tool or
frontend form is must be needed to send data because the browser search bar can only send get
requests to receive resources from the server.
Example: Setting up a route to be accessed by users to send data with post requests.
1. Before creating a route for receiving data, we are using an inbuilt middleware, Middleware is
such a broad and more advanced topic so we are not going to discuss it here, just to understand
a little bit you can think of this as a piece of code that gets executed between the request-
response cycles.
2. The express.json() middleware is used to parses the incoming request object as a JSON object.
The app.use() is the syntax to use any middleware.
3. After then we have created a route on path ‘/’ for post request.
4. const {name}, which is the syntax in ES6 to extract the given property/es from the object. Here
we are extracting the name property which was sent by the user with this request object.
5. After that, we are simply sending a response to indicate that we have successfully received
data. If this `${} ` is looking weird to you then let me tell you that it is the syntax in ES6 to
generate strings with javascript expression in ES6. We can inject any javascript expression
inside ${}.
 app.js

const express = require('express');

const app = express();


const PORT = 3000;

app.use(express.json());
app.post('/', (req, res)=>{
const {name} = req.body;

res.send(`Welcome ${name}`);
})

app.listen(PORT, (error) =>{


if(!error)

Page 11 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

console.log("Server is Successfully Running, and


App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: We are Accessing the route with Postman. It is a tool to test APIs, we
can use any other things like Axios, fetch, or any other thing from the frontend or cURL from the
terminal, but that will make you divert from the topic, just keep in mind that our express server only
demands a path with request object it doesn’t matter from where it is coming. We have sent the data
as a JSON object with the request body and express is sending a response back to us along with the
data. It indicates that our goal to send data to the server succeeded.
Output:

Step 5: Sending Files from Server


Step 6: Now we will see how to send files from the server.
Several times we need to transfer the resources from the server as per user request, there are majorly
two methods to send files one is sending static files using middleware and the other one is sending a
single file on a route.
This is our folder structure and we want to serve the files from the Static Files directory as static files,
and the image.jpg on a separate route.

Example 1: Serving entire directory using middleware


Express provides us a middleware express.static(), it accepts two arguments first one is the absolute
root path of the directory whose files we are going to serve.
We can simply use it to serve static files, by providing to app.use().
Syntax:
app.use(path, express.static(root, [options]));
1. First of all, we are importing an inbuilt module `path`, because later we are going to use one of
the functions provided by this module.
2. We are simply mounting a middleware at the ‘/static’ route.
3. The static() middleware requires an absolute path so we use the path module’s join method.
4. The join() method takes two parameters and joins them as a path, in NodeJS we have a global
attribute dirname which contains the path of the directory in which the current file exists.
5. We are providing that joined path to middleware so that it can start serving the files inside that
directory on the given path.

Page 12 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
 app.js

const express = require('express');

const app = express();


const PORT = 3000;

const path = require('path')


app.use('/static', express.static(path.join( dirname, 'Static Files')))

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: This will be the returned response when we request some static file from
the directory which we are serving as static. Here you can see we have received an HTML file as a
response for ‘/static/random.html’. The same things happen when we request for ‘/static/1.jpg’.
Output:

Example 2: Sending a single file on a route with the sendFile() function. This
function accepts an absolute URL of the file and whenever the route path is being accessed the server
provides the file as an HTTP response. This process can be thought of as a single endpoint of the
express.static(). It can be useful when we have to do some kind of processing before sending the file.
Syntax:
res.sendFile(fileUrl)
1. We are creating a get request route on the ‘/file’ path
2. After then we are creating the absolute path by joining the path of current dirname and the
name of the file we want to send and then passing it to sendFile().
3. Then route sends the image.jpg file to the user as an HTTP response.
 app.js

const express = require('express');


const path = require('path');

const app = express();


const PORT = 3000;

app.get('/file', (req, res)=>{ res.sendFile(path.join(


dirname,'image.jpg'));

Page 13 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and App is listening on port "+
PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Output: After running the server, When we request the route ‘/file’ the server sends the image.jpg file
as a response.

Creating Templates
You also need to create template files. When creating template files, keep in mind these considerations:
Reusability: Try to make your templates reusable in other parts of your application and in other
applications. Most template engines cache the templates to speed up performance. The more templates
you have requires more caching time. Try to organize your templates so that they can be used for
multiple purposes. For example, if you have several tables of a data displayed in your app, only make a
single template for all of them that can not only dynamically add the data, but can also set column
headers, titles, and such.
Size: As template sizes grow, they tend to become more and more unwieldy.
Try to keep your templates compartmentalized to the type of data they are presenting. For example, a
page that has a menu bar, form, and table could be split into three separate templates.
Hierarchy: Most websites and applications are built on some sort of hierarchy.
For example, the <head> section as well as a banner and menu may be the same throughout the site.
Use a separate template for components that show up in multiple locations, and just include those
subtemplates when building your final page.
Listing 18.8 shows a basic EJS template that applies a set of local variables in a list to display user
information. The EJS code is basic and only uses the <%= variable %> to pull values from the Express
local variables.
Listing 18.8 user_ejs.html: Simple EJS template for displaying a user
01 <!DOCTYPE html>
02 <html lang="en">
03 <head>
04 <title>EJS Template</title>
05 </head>
06 <body>
07 <h1>User using EJS Template</h1>
08 <ul>
09 <li>Name: <%= uname %></li>
10 <li>Vehicle: <%= vehicle %></li>
11 <li>Terrain: <%= terrain %></li>
12 <li>Climate: <%= climate %></li>
13 <li>Location: <%= location %></li>
14 </ul>
15 </body>
16 </html>

Page 14 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
Listing 18.9 and Listing 18.10 show using Pug to implement a main template and then consume it in a
subtemplate. The main template in Listing 18.9 is basic, only implementing the doctype, html, head,
and title elements. It also defines the block content element defined in Listing 18.10.
Notice that line 1 in Listing 18.10 extends main_pug to include those elements first and then adds the
h1, ul, and li elements, which get values from the local variables.
Listing 18.9 main_pug.pug: Simple Pug template that defines the main webpage
1 doctype 5
2 html(lang="en")
3 head
4 title="Pug Template"
5 body
6 block content
Listing 18.10 user_pug.pug: Simple Pug template that includes the main_pug.pug template
and adds elements for displaying a user
1 extends main_pug
2 block content
3 h1 User using Pug Template
4 ul
5 li Name: #{uname}
6 li Vehicle: #{vehicle}
7 li Terrain: #{terrain}
8 li Climate: #{climate}
9 li Location: #{location}
Rendering Templates in a Response
Once you have the template engine defined and configured and have created your templates, you can
send a rendered template using the Express app object or using the Response object. To render a
template in the Express app you use the app.render() method:
app.render(view, [locals], callback)
The view parameter specifies the view filename in the views directory. If no extension is included on the
file, the default extensions such as .pug and .ejs are tried. The locals parameter allows you to pass in a
locals object if one has not been defined in app.locals already. The callback function is executed after
the template has been rendered and accepts an error object for the first parameter and the string form
of the rendered template as the second.
To render a template directly into the response, you can also use the res.render() function, which works
exactly the same as app.render(), except that no callback is needed. The rendered results automatically
are sent in the response.
The app.render() and res.render() methods both work well. If you do not need to do anything with the
data before sending it, the res.render() method saves the extra code to call res.send() to send the data.
Listing 18.11 puts all the template rendering concepts together in a couple of basic examples. Lines 5–8
set up the views directory and view engine and register pug and ejs. Then in lines 10–13 user
information is defined in app.locals.
Lines 14–16 handle the /pug route, which directly renders the user_pug.pug template from Listing
18.10 with the defined locals in the client response.
Lines 17–21 handle the /ejs route by first calling app.render() to render the
users_ejs.html template defined in Listing 18.8 into a string,
renderedData. Then that data is sent using the res.send() command. Figure
18.6 shows the rendered webpages from both functions.
Listing 18.11 express_templates.js: Implementing Pug and EJS templates in Express
01 var express = require('express'),
02 pug = require('pug'),
03 ejs = require('ejs');
04 var app = express();
05 app.set('views', './views'); 06
app.set('view engine', 'pug');
07 app.engine('pug', pug. express);
08 app.engine('html', ejs.renderFile);
09 app.listen(80);
10 app.locals.uname = 'Caleb';
11 app.locals.vehicle = 'TARDIS';
12 app.locals.terrain = 'time and space';
13 app.locals.location = 'anywhere anytime';
14 app.get('/pug', function (req, res) {
15 res.render('user_pug');
16 });

Page 15 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
17 app.get('/ejs', function (req, res) {
18 app.render('user_ejs.html', function(err, renderedData){
19 res.send(renderedData);
20 });
21 });

Figure 18.6 Webpages generated by rendering Pug and EJS templates

Understanding Middleware
Express provides a simple but effective middleware framework that allows you to provide additional
functionality between the point when a request is received and when you actually handle the request
and send the response. Middleware allows you to apply authentication, cookies, and sessions and
otherwise manipulate the request before it is passed to the handler.
Express is built on top of the connect NPM module, which provides the underlying middleware support.
The following list describes some of the built-in middleware components that come with Express.
Additional Express middleware components are available as NPMs if you query the NPM repository, and
you can also create your own custom middleware:
logger: Implements a formatted request logger to track requests to the server
static: Allows the Express server to stream static file get requests
favicon: Provides functionality to support sending the favicon to the browser
basicAuth: Provides support for basic HTTP authentication
cookieParser: Allows you to read cookies from the request and set cookies in the response
cookieSession: Provides cookie-based session support
session: Provides a fairly robust session implementation
bodyParser: Parses the body data of POST requests into the req.body property
query: Converts the query string to a JavaScript object and stores it as req.query
compress: Provides Gzip compress support for large responses to the client
csrf: Provides cross-site request forgery protection Middleware can be applied either globally to all
routes under a specific path or to specific routes. The following sections describe each of these
methods.
Assigning Middleware Globally to a Path
To assign middleware to all routes, you can implement the use() method on the Express application
object. The use() method uses the following syntax:
use([path], middleware)

Page 16 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
The path variable is optional and defaults to /, which mean all paths. The middleware is a function that
has the following syntax, where req is the Request object, res is the Response object, and next is the
next middleware function to execute:
function(req, res, next)
Each of the built-in middleware components has a constructor that returns the appropriate middleware
function. For example, to apply the logger middleware to all paths with default parameters, you use the
following statements:
var express = require('express');
var app = express();
app.use('/', express.logger());
Assigning Middleware to a Single Route
You can also apply logger to a single route by passing it after the path parameter. For example, in the
following code, requests to the /loggedRoute are logged; however, requests to the /otherRoute are not
logged.
app.get('/loggedRoute', express.logger(), function(req, res) {
res.send('This request was logged.');
});
app.get('/otherRoute', function(req, res) {
res.send('This request was not logged.');
});
Adding Multiple Middleware Functions
You can assign as many middleware functions globally and to routes as you want.
For example, the following code assigns the query, logger, and bodyParser
middleware modules:
app.use('/', express.logger()).
use('/', express.query()).
use('/', express.bodyParser());
Keep in mind that the order you assign the functions is the order that they will be
applied during a request. Some middleware functions need to be added before others.
Using the query Middleware
One of the most useful and simple middleware components is the query middleware. The query
middleware converts the query string in the URL into a JavaScript object and stores it as the query
property on the Request object.
The following code shows the basics of implementing the query middleware. The query string for the
request looks like ?id=10,score=95. Notice that JSON.stringify can be called on req.query because it is
a JavaScript object.
var express = require('express');
var app = express();
app.use('/', express.query());
app.get('/', function(req, res) {
var id = req.query.id;
var score = req.query.score;
console.log(JSON.stringify(req.query));
res.send("done");
});
Serving Static Files
A commonly used Express middleware is the static middleware, which allows you to serve static files
directly from disk to the client. You can use static middleware to support things like JavaScript files, CSS
files, image files, and HTML documents that do not change. The static module is easy to implement and
uses the following syntax:
express.static(path, [options])
The path is the root path to where the static files are referenced from in the requests. The options
parameter allows you to set the following properties:
maxAge: Sets the browser cache maxAge in milliseconds. The default is 0.
hidden: A Boolean that, when true, indicates that transfer of hidden files is
enabled. The default is false.
redirect: A Boolean that, when true, indicates that if the request path is a
directory, the request is redirected to the path with a trailing /. The default is
true.
index: Specifies the default filename for the root path. The default is
index.html.
Listings 19.1 through 19.3 show the Express code, HTML, and CSS that illustrate
implementing the static middleware to support serving a static HTML, CSS, and
image file. Notice that two static paths are implemented: one for the route / that

Page 17 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
maps to a subdirectory named static and the second for route /images that
maps to a peer directory named images. Figure 19.1 shows the statically served
HTML document in a web browser.
Listing 19.1 express_static.js: Express code that implements two static
routes
1 var express = require('express');
2 var app = express();
3 app.use('/', express.static('./static'), {maxAge:60*60*1000}); 4
app.use('/images', express.static( '../images'));
5 app.listen(80);
Listing 19.2 ./static/index.html: Static HTML file that requests the CSS
and image files from the server
01 <html>
02 <head>
03 <title>Static File</title>
04 <link rel="stylesheet" type="text/css" href="css/static.css">
05 </head>
06 <body>
07 <img src="/images/arch.jpg" height="200px"/>
08 <img src="/images/flower.jpg" height="200px" />
09 <img src="/images/bison.jpg" height="200px" />
10 </body>
11 </html>
Listing 19.3 ./static/css/static.css: CSS file that formats the images
1 img
2{
3 display:inline;
4 margin:3px;
5 border:5px solid #000000;
6}
Figure 19.1 HTML, CSS, and image files served statically to a browser

Handling POST Body Data


Another common use for Express middleware is to handle body data inside a POST request. The data
inside a request body can be in various formats such as POST parameter strings, JSON strings, or raw
data. Express provides the bodyParser middleware that attempts to parse the data in the body of
requests and properly format them as the req.body property of the Request object.
For example, if POST parameters or JSON data is received they are converted to a JavaScript object and
stored as the req.body property of the Request object.
Listing 19.4 illustrates using the bodyParser middleware to support reading form data posted to the
server.
Lines 4–9 handle the GET request and respond with a basic form. It is not well formatted HTML; however,
it is adequate to illustrate the use of the bodyParser middleware.
Lines 11–20 implement a POST request handler. Notice that in line 16, the first name entered in the form
field is accessed using req.body.first to help build the hello message in the response. That really is it.
You can handle any kind of form data in the body in this manner. Figure 19.2 shows the web form usage
in the browser.
Listing 19.4 express_post.js: Handling POST parameters in the request body using the
bodyParser middleware
01 var express = require('express');
02 var app = express();
03 app.use(express.bodyParser());
04 app.get('/', function (req, res) {
05 var response = '<form method="POST">' +
06 'First: <input type="text" name="first"><br>' +
07 'Last: <input type="text" name="last"><br>' +
08 '<input type="submit" value="Submit"></form>';
09 res.send(response);
10 });
11 app.post('/',function(req, res){
12 var response = '<form method="POST">' +
13 'First: <input type="text" name="first"><br>' +
14 'Last: <input type="text" name="last"><br>' +
15 '<input type="submit" value="Submit"></form>' +

Page 18 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
16 '<h1>Hello ' + req.body.first + '</h1>';
17 res.type('html');
18 res.end(response);
19 console.log(req.body);
20 });
21 app.listen(80);

Page 19 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
Figure 19.2 Handling POST parameters in the request body using the bodyParser
Middleware
Building a template
When building templates, start with whichever one makes the most sense to you. This might be the
most complicated or the most simple, or just the first in the main user journey. For Loc8r a good place to
start is the homepage; this is the example we’ll go through in most detail.
DEFINING A LAYOUT
The primary aim for the homepage is to display a list of locations. Each location will need to have a
name, an address, the distance away, users’ ratings, and a facilities list.
We’ll also want to add a header to the page, and some text to put the list in context, so that users know
what they’re looking at when they first visit.
You may find it useful, as I do, to sketch out a layout or two on a piece of paper or a whiteboard. I find
this really helpful for creating a starting point for the layout, making sure you’ve got all of the pieces
you need on a page without getting bogged down in the technicalities of any code. Figure 4.8 shows
what I’ve sketched for the homepage of Loc8r.
You’ll see that there are two layouts, a desktop and a phone. It’s worth making the responsive
distinction at this point, with your understanding of what Bootstrap can do and how it works in the back
of your mind.

At this stage, the layouts are by no means final and we may well find that we’ll tweak them and change
them as we build the code. But any journey is easier if there’s a destination and a map; this is what the
sketches give us. We can start off our coding in the right direction. The few minutes it takes to do this
upfront can save us hours later on—moving parts around, or even throwing them out and starting
again, is much easier with a sketch than with a load of code.
Now that we’ve got an idea of the layout and the pieces of content required, it’s time to put it together
in a new template.
SETTING UP THE VIEW AND THE CONTROLLER
The first step is to create a new view file and link it to the controller. So in the app_server/views folder
make a copy of the index.jade view and save it in the same folder as locations-list.jade. It’s best not
calling it “homepage” or something similar, as at some point we may change our mind about what
should be displayed on the homepage. This way, the name of the view is clear, and it can be used
anywhere without confusion.
The second step is to tell the controller for the homepage that we want to use this new view. The
controller for the homepage is in the locations.js file in app_server/ controllers. Update this to change
the view called by the homelist controller. This should look like the following code snippet (modifications
in bold):
module.exports.homelist = function(req, res){
res.render('locations-list', { title: 'Home' });
};

Page 20 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
Now let’s build the view template.
CODING THE TEMPLATE: PAGE LAYOUT
When actually writing the code for the layouts, I prefer to start with the big pieces, and
then move toward the detail. As we’re extending the layout file, the navigation bar
and footer are already done, but there’s still the page header, the main area for the
list, and the sidebar to consider.
At this point we need to take a first stab at how many of the 12 Bootstrap columns
we want each element to take up on which devices. The following code snippet
shows the layout of the three distinct areas of the Loc8r List page:

I did go back and forth a bit, testing the columns at various resolutions until I was happy with them.
Having device simulators can make this process easier, but a really simple method is to just change the
width of your browser window to force the different Bootstrap breakpoints. When you’ve got something
you think is probably okay,you can push it up to Heroku and test it out for real on your phone or tablet.
CODING THE TEMPLATE: LOCATIONS LIST
Now that the containers for the homepage are defined, it’s time for the main area.
We have an idea of what we want in here from the sketches drawn for the page layout.
Each place should show the name, address, its rating, how far away it is, and the key facilities.
Because we’re creating a clickable prototype all of the data will be hard-coded into the template for
now. It’s the quickest way of putting a template together and ensuring that we have the information we
want displayed the way we want. We’ll worry about the data side of it later. If you’re working from an
existing data source, or have constraints around what data you can use, then naturally you’ll have to
bear that in mind when creating the layouts.
Again, getting a layout you’re happy with will take a bit of testing, but Jade and Bootstrap working
together make this process considerably easier than it might be.
The following code snippet shows what I’ve come up with for a single location:

Page 21 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

Once again you can see how much you can achieve with relatively little effort and
code, all thanks to the combination of Jade and Bootstrap. To give you an idea of what
the preceding code snippet does, it will render like figure 4.9.

Figure 4.9 Onscreen rendering of a single location on the List page


This section is set to go across the full width of the available area, so 12 columns on
all devices. Remember, though, that this section is nested inside a responsive column,
so that full width is the full width of the containing column, not necessarily
the browser viewport.
This will probably make more sense when we put it all together and see it in action.
CODING THE TEMPLATE: PUTTING IT TOGETHER
So we’ve got the layout of page elements, the structure of the list area, and some hardcoded
data. Let’s see what it looks like all together. To get a better feel of the layout in
the browser it will be a good idea to duplicate and modify the List page so that we have
a number of locations showing up. The code, including just a single location for brevity,
is shown in the following listing.

Page 22 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

When you’ve got this all in place, you’ve got the homepage listing template all done.
If you run the application and head to localhost:3000 you should see something like
figure 4.10.
See how the layout changes between a desktop view and a mobile view? That’s all thanks to Bootstrap’s
responsive framework and our choice of CSS classes. Scrolling down in the mobile view you’ll see the
sidebar text content between the main list and the footer. On the smaller screen it’s more important to
display the list in the available space than the text.
So that’s great; we’ve got a responsive layout for the homepage using Jade and Bootstrap in Express
and Node. Let’s quickly add the other views.

Adding the rest of the views


The Locations collection’s List page is done, so we now need to look at creating the
other pages to give users a site they can click through. In this section we’ll cover adding
these pages:
1 Details
2 Add Review
3 About
We won’t go through the process in so much detail for all of them though, just a bit of
explanation, the code, and the output. You can always download the source code from
GitHub if you prefer.
4.4.1 Details page
The logical step, and arguably the next most important page to look at, is the Details page for an
individual location.
This page needs to display all of the information about a location, including
■Name
■Address
■Rating
■Opening hours
■Facilities
■Location map

Page 23 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
Figure 4.10 Responsive template for the homepage in action on different devices
Licensed to Marwk wWwa.tist-oenb o<[email protected]>
Adding the rest of the views
■Reviews, each with
– Rating
– Reviewer name
– Review date
– Review text
■Button to add a new review
■Text to set the context of the page
That’s quite a lot of information! This is the most complicated single template that
we’ll have in our application.
PREPARATION
The first step is to update the controller for this page to use a different view. Look for
the locationInfo controller in the locations.js file in app_server/controllers. Change the
name of the view to be location-info, as per the following code snippet:
module.exports.locationInfo = function(req, res){
res.render('location-info', { title: 'Location info' });
};
Remember, if you run the application at this point it won’t work because Express can’t
find the view template. Not surprising really, as we haven’t created it yet. That’s the
next part.
THE VIEW
Create a new file in app_server/views and save it as location-info.jade. The content for
this is shown in listing 4.7. This is the largest listing in this book. Remember that for
the purposes of this stage in the prototype development, we’re generating clickable
pages with the data hard-coded directly into them.

Page 24 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

So that’s a pretty long template, and we’ll look at how we can shorten that soon. But
the page itself is pretty complex and contains a lot of information, and a few nested
responsive columns. Imagine how much longer it would be if it was written in full
HTML, though!
ADDING A BIT OF STYLE
This template will look okay as it is, but there are some little stylistic issues that can easily
be addressed with a few lines of CSS. When we set up the project we left the default
Express stylesheet where it was for just this reason, even though we took all of the content
out of it. The file is called style.css and is in the folder public/stylesheets. Enter
the following code snippet into the file and save it:
.review {padding-bottom: 5px;}
.panel-body.review-container {padding-top: 0;}
.review-header {margin-bottom: 10px;}
.reviewAuthor {margin: 0 5px;}

Page 25 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
.reviewTimestamp {color: #ccc;}
With this saved, the Details page layout is complete, and you can head over to localhost:
3000/location to check it out. Figure 4.11 shows how this layout looks in a browser
and on a mobile device.
The next step in this user journey is the Add Review page, which has much simpler
requirements.

Figure 4.11 Details page layout on desktop and mobile devices

Q. Explain REST API?


-------------------------------------------------------------------------------------------------------------
REST API (Introduction)
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be
used for creating web services. REST API is a way of accessing web services in a simple and flexible
way without having any processing.
REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP)
technology because REST uses less bandwidth, simple and flexible making it more suitable for internet
usage. It’s used to fetch or give some information from a web service. All communication done via REST
API uses only HTTP request.
Working: A request is sent from client to server in the form of a web URL as HTTP GET or POST or PUT
or DELETE request. After that, a response comes back from the server in the form of a resource which
can be anything like HTML, XML, Image, or JSON. But now JSON is the most popular format being used in
Web Services.

In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST, GET,
PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations
respectively. There are other methods which are less frequently used like OPTIONS and HEAD.
 GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In the
safe path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK).
In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

 POST: The POST verb is most often utilized to create new resources. In particular, it’s used to
create subordinate resources. That is, subordinate to some other (e.g. parent) resource. On

Page 26 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
successful creation, return HTTP status 201, returning a Location header with a link to the newly-
created resource with the 201 HTTP status.
NOTE: POST is neither safe nor idempotent.
 PUT: It is used for updating the capabilities. However, PUT can also be used to create a
resource in the case where the resource ID is chosen by the client instead of by the server. In
other words, if the PUT is to a URI that contains the value of a non-existent resource ID. On
successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If
using PUT for create, return HTTP status 201 on successful creation. PUT is not safe operation
but it’s idempotent.
 PATCH: It is used to modify capabilities. The PATCH request only needs to contain the changes
to the resource, not the complete resource. This resembles PUT, but the body contains a set of
instructions describing how a resource currently residing on the server should be modified to
produce a new version. This means that the PATCH body should not just be a modified part of
the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither
safe nor idempotent.
 DELETE: It is used to delete a resource identified by a URI. On successful deletion, return HTTP
status 200 (OK) along with a response body.

Idempotence: An idempotent HTTP method is a HTTP method that can be called many times without
different outcomes. It would not matter if the method is called only once, or ten times over. The result
should be the same. Again, this only applies to the result, not the resource itself.
Example:
 C

1. a = 4 // It is Idempotence, as final value(a = 4)


// would not change after executing it multiple
// times.

2. a++ // It is not Idempotence because the final value


// will depend upon the number of times the
// statement is executed.

Request and Response


Now we will see how request and response work for different HTTP methods. Let’s assume we have
an API(https://www.geeksforgeeks.org/api/students) for all students data of gfg.
 GET: Request for all Students.

Request

GET:/api/students

 POST: Request for Posting/Creating/Inserting Data

Request

POST:/api/students
{“name”:”Raj”}

 PUT or PATCH: Request for Updating Data at id=1

Request

PUT or PATCH:/api/students/1
{“name”:”Raj”}

 DELETE: Request for Deleting Data of id=1

Request

DELETE:/api/students/1

Page 27 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
RESTful web services are very popular because they are light weight, highly scalable and maintainable
and are very commonly used to create APIs for web-based applications.

REST API Architectural Constraints


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 which 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.
Architectural Constraints of RESTful API: There are six architectural constraints which makes any
web service are listed below:
 Uniform Interface
 Stateless
 Cacheable
 Client-Server
 Layered System
 Code on Demand
The only optional constraint of REST architecture is code on demand. If a service violates any other
constraint, it cannot strictly be referred to as RESTful.
Uniform Interface: It is a key constraint that differentiate between a REST API and Non-REST API. It
suggests that there should be an uniform way of interacting with a given server irrespective of device or
type of application (website, mobile app).
There are four guidelines principle of Uniform Interface are:
 Resource-Based: Individual resources are identified in requests. For example: API/users.
 Manipulation of Resources Through Representations: Client has representation of resource
and it contains enough information to modify or delete the resource on the server, provided it
has permission to do so. Example: Usually user get a user id when user request for a list of
users and then use that id to delete or modify that particular user.
 Self-descriptive Messages: Each message includes enough information to describe how to
process the message so that server can easily analyses the request.
 Hypermedia as the Engine of Application State (HATEOAS): It need to include links for
each response so that client can discover other resources easily.
Stateless: It means that the necessary state to handle the request is contained within the request itself
and server would not store anything related to the session. In REST, the client must include all
information for the server to fulfill the request whether as a part of query params, headers or URI.
Statelessness enables greater availability since the server does not have to maintain, update or
communicate that session state. There is a drawback when the client need to send too much data to the
server so it reduces the scope of network optimization and requires more bandwidth.
Cacheable: Every response should include whether the response is cacheable or not and for how much
duration responses can be cached at the client side. Client will return the data from its cache for any
subsequent request and there would be no need to send the request again to the server. A well-
managed caching partially or completely eliminates some client–server interactions, further improving
availability and performance. But sometime there are chances that user may receive stale data.
Client-Server: REST application should have a client-server architecture. A Client is someone who is
requesting resources and are not concerned with data storage, which remains internal to each server,
and server is someone who holds the resources and are not concerned with the user interface or user
state. They can evolve independently. Client doesn’t need to know anything about business logic and
server doesn’t need to know anything about frontend UI.
Layered system: An application architecture needs to be composed of multiple layers. Each layer
doesn’t know any thing about any layer other than that of immediate layer and there can be lot of
intermediate servers between client and the end server. Intermediary servers may improve system
availability by enabling load-balancing and by providing shared caches.
Code on demand: It is an optional feature. According to this, servers can also provide executable code
to the client. The examples of code on demand may include the compiled components such as Java
Servlets and Server-Side Scripts such as JavaScript.
Rules of REST API: There are certain rules which should be kept in mind while creating REST API
endpoints.

Page 28 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
 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/users is a good example, but
/api?type=users 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, GET, 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/users GET Get all users

api/users/new GET Show form for adding new user

api/users POST Add a user

api/users/1 PUT Update a user with id = 1

pi/users/1/edit GET Show edit form for user with id = 1

api/users/1 DELETE Delete a user with id = 1

api/users/1 GET Get a user 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.
Note : You can easily use GET and POST but in order to use PUT and DELETE you will need to install
method override. You can do this by following below code :
npm install method-override --save
This simply require this package in your code by writing :
var methodOverride = require("method-override");
Now you can easily use PUT and DELETE routes :
app.use(methodOverride("_method"));
HTTP verbs: Some of the common HTTP methods/verbs are described below:
 GET: Retrieves one or more resources identified by the request URI and it can cache the
information receive.
 POST: Create a resource from the submission of a request and response is not cacheable in this
case. This method is unsafe if no security is applied to the endpoint as it would allow anyone to
create a random resource by submission.
 PUT: Update an existing resource on the server specified by the request URI.
 DELETE: Delete an existing resource on the server specified by the request URI. It always return
an appropriate HTTP status for every request.
 GET, PUT, DELETE methods are also known as Idempotent methods. Applying an operation once
or applying it multiple times has the same effect. Example: Delete any resource from the server
and it succeeds with 200 OK and then try again to delete that resource than it will display an
error message 410 GONE.

Q. Explain how to test REST APIs?


-------------------------------------------------------------------------------------------------------------
REST API Testing
REST API Testing is a technique that is done by recording the response of the REST APIs by sending
various HTTP requests to check the validity and working of the APIs for web applications. Instead of
standard user input(like keyboards and output), we use software to send calls, obtain output and record
the response. Automation testing of API needs an app that can interact through an API.
A REST API acts as a contract between the client and the server(the client by making a request from the
server for the response). So, before moving forward, our first duty should be checking the contract by
inspecting the service. There should be no duplicate, and missing functionality and endpoints should

Page 29 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
be correctly named. Our first concern should be about the functionality of the API(whether it is working
properly or not(without bugs)).
For testing to be done, our application must interact with the sample API. API testing requires two
things:
 A tool or a framework to operate the API such as Advanced REST Client, Postman REST Client, or
Curl in Linux.
 A tester writes the code to test the sample REST API.
Different Ways of Testing REST APIs
1. Validation Testing: It is considered as the assurance of the correct development and occurs at
the final steps verifying the behavior and efficiency aspects of the product.
2. Security Testing: This is done to secure the API implementation from external threats. It also
includes the design of the API access control, validation of encryption methodologies, and user
rights management.
3. UI Testing: It focuses on the user interface for the API rather than testing the API itself.
4. Functional Testing: Particular functions in the codebase are included in the Functional Testing
and handle the API Function in a planned manner.
5. Load Testing: It monitors whether the solution provided is working as planned or not and
generally occurs after the whole codebase is completed.
6. Runtime and Error Detection: It mainly focuses on error detection, execution error, and
monitoring and deals with the universal result of the API Codebase(as it is related to the actual
running of the API).
7. Penetration Testing: It is involved in the auditing process as a second test.
Steps for Testing REST API
Below are the steps for testing REST API:
Step 1: The very first step of the API Testing procedure is setting up and using a testing Environment,
which will be further useful in the API Testing process in product development.
Step 2: For the above procedure, we need to open up any tool(like Postman, REST-assured, swagger,
etc) or framework and set up the necessary parameters of the API.
Step 3: We can use the tools Online(in Google Chrome) or by downloading, installing, and launching
them.
Step 4: The testing environment includes configuring the server and database based on the
requirements of the application.
Step 5: Now, we need to enter the API URL which we want to test in the textbox.

Step 6: The further procedure needs to select the HTTP(Hypertext Transfer Protocol) method(For
example, POST, GET, PUT, DELETE), it is the type of the API whose URL we have entered(POST for
creating, PUT for updating, DELETE for deleting).

Page 30 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

Step 7: Now after providing the HTTP Methods, in the Headers textbox, give the headers set that you
want to provide(For example, Authorization in the Postman tool).

Step 8: We can provide parameters(query parameters for filtering) in the tool if it is defined in the
code.

Page 31 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

Step 9: Now, switch to the Body section and provide the Body content to it.
Step 10: Firstly, set the required body content type – application/JSON/text. Add the editor view
type(e.g. Raw Input). Pass the request body of the API in the payload. For example: If it is POST API, pass
the body or parameter under the payload: {“key1”:”value1”, “key2”:”value2”}.

Step 11: Now invoke an API call by clicking the send button.

Page 32 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

Step 12: Now authenticate the result by clicking the details to view the response details.

Authenticating the Results


Now the question arises, how to analyze and authenticate the results? For that, we have to understand
some API actions i.e. correct HTTP status code. Those are:
1XX 2xx 3xx 4xx 5xx
Informational Success Redirection Client Error Server Error

300
100 200 Multiple 400 500
Continue OK Choices Bad Request Internal Server Error

Page 33 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

1XX 2xx 3xx 4xx 5xx


Informational Success Redirection Client Error Server Error

101 301
Switching 201 Moved 401 501
Protocol Created Permanently Unauthorized Not Implemented

203 402
102 Non-Authoritative 302 Payment 502
Processing Information Found Required Bad Gateway

204 303 403 503


No Content See Other Forbidden Service Unavailable

205 304 404 504


Reset Content Not Modified Not Found Gateway Timeout

405 505
206 305 Method Not HTTP Version Not
Partial Content Use Proxy Allowed Supported

207 506
Multi-Status 306 406 Variant Also Negotiates
(WebDAV) (Unused) Not Acceptable (Experimental)

Challenges in API Testing


1. Initial Setup of API Testing: Maintaining API Testing preparation and launch of its
environment requires certain technical skills from the team which is one of the most challenging
parts of the process. It is not because it is difficult, but because it can be a substantial
motivation killer. During this stage, problems will occur frequently and in large amounts. What
we need is that motivate the dedicated software testing team through the process (as it pays off
over the long term).
2. Maintaining Data Formatting(updating schema of the API Testing): Schema acts as a
blueprint for describing the API syntax and grammar of the text. It specifies how data is
formatted in the code and handles all the requests and responses and contains the format of the
data. It is necessary to maintain this throughout the process. Although it is a challenge, we can
overcome this. It is done by maintaining and updating the schema regularly to ensure that the
newly added parameters are included in the schema.
3. Sequencing the API calls: When working on multi-threaded apps, the user may send multiple
API requests at the same time, which can become a sequencing challenge for the testing team if
not sent in the correct order. To overcome this problem, the API calls should be in the correct
order so that the program will throw an error. An example of this challenge, requesting a DELETE
or GET kind of API before POST(calling an API about the user’s profile, before creating it), which
would throw an error.
4. Validating Parameters: Requesting the API requests, the Testing team may find validating the
parameters challenging as well. A large number of parameters and their use cases make it an
unsettling task. We need to be sure that every crucial parameter data uses the correct string or
numerical data type, which fits within an assigned value range, length limitation, and validation
criterion. This challenge can be overcome by continuous synthetic API monitoring to hold upon
the issues as early as possible.
5. Testing All Possible Parameter Request Combination: The communication between the
systems(handled by API) is done by assigning data values to the parameters and passing those
parameters through data requests. Here, it’s necessary and a challenge to test all the parameter
request combinations in the API to test for flaws in specific configurations. Otherwise, a project
may end up having two values for the same parameter. So, try to add fewer extra parameters to
reduce the chance of likely combinations. Also, there should be the correct choice of applications
that are not complex for everyday operations.
6. Leaving Out Response Time Assertions: APIs generally took lesser time when called upon.
But what when it took more than 10 sec, will it be efficient? Not at all! and becomes more

Page 34 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
challenging for software testers. So, set up response time assertions that should be reasonable
and would be able to depict the response time. A large threshold response time assertion is
much much better than nothing mainly when testing production endpoints.
7. Tracking System Integration: Always ensuring that the API system is working correctly with
the data tracking system or not is also a big challenge. So, we need to bring back the correct
responses on whether a call is working properly. As this is the last step of the Testing process,
the team may be too frustrated that they don’t give it the proper attention it needs. To
overcome this problem, one needs to focus on the designing part. Also, check out its integration
with the other systems. Do not test the apps in parallel with the Critical Integration System.
Top Tools for REST API Test
1. Postman: Postman is a plugin in Google Chrome. This tool is best for API Testing. Its services have
been expanded to Windows and Mac. Its API Development Environment has been divided into three
parts Collections, Workspaces, and Built-in Tools which is helpful in running requests, debugging the
code, creating automated test, etc.
Features:
 It is easy to set up parameters on method calls.
 It is helpful in Automation Testing.
 All the modern web API data can be extracted using postman.
 It has the ability to store commands.
 It has the feature to create a collection of REST calls and save it.
 It offers a rich interface.
2. REST-assured: REST-assured is best for Automation Testing rather than manual testing. It has been
considered one of the best API Testing tools help in JAVA. Writing code in JAVA involves a lot of
ceremonies but REST-assured handles help to write it in a clear and descriptive manner which results in
responsive code.
Features:
 It provides several authentication mechanisms(like POST, GET, PUT, DELETE, OPTIONS, PATCH,
and HEAD requests).
 To test using REST-assured, Testers need not have extreme knowledge of HTTP.
 It has some built-in functions which do not require coding things from scratch.
 It also allows using the syntax of BBD/ Given/When/Then syntax.
3. Swagger: Swagger is one of the best tools for designing and documenting REST APIs. It is a set of
open-source tools, whose origination is based upon OpenAPI specification. These API specifications can
be written YAML or JSON. The major Swagger tool includes:
 Swagger Editor.
 Swagger UI.
 Swagger Codegen.
 Swagger Editor Next (beta).
 Swagger Core.
 Swagger Parser.
 Swagger APIDom.
Features:
 It offers fast and standardized API Design.
 It facilitates and coordinates the entire API lifecycle from a central internal repository.
 It offers secure API collaboration.
 It helps in generating beautiful documentation, that is interactive, fully hosted, and privacy
enabled.
4. Karate DSL: Karate DSL is a famous open-source framework running on JAVA. It is used for
Automation Testing, Performance Testing, and Load Testing, and is based on the cucumber library. It
helps in API-based BBD tests in a simple way. It has its own specific language-DSL(Domain Specific
Language).
Features:
 It supports multi-thread parallel execution(it’s very fast).
 It offers an easy-to-write test(for those who are not into core programming).
 It allows(support) both XML as well as JSON.
 It has very powerful assertions and JSON schema validation.
 It also supports configuration switching.
 In this, we can reuse payload data for API testing.
5. Katalon: Katalon is one of the popular, robust and comprehensive test Automation tools (for API,
Web, desktop testing, and mobile testing). This platform brings a struggle-free testing environment for
the testers with or without programming knowledge. This provides easy deployment. Deployment is
done by including all frameworks, ALM integrations, and plugins in one package.
Features:
 The Katalon platform supports the data-driven approach.

Page 35 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR
 It supports all types of REST, SOAP requests, and SSL client certificates.
 It can be used for both automated and exploratory testing.
 It easily imports tests from swagger(2.0 &3.0), Postman, WSDL, and WADL.
 It is suitable for both beginners and experts with manual and scripting modes.
 Katalon has pre-built and customizable code templates.
 It provides auto-completion, auto-formatting, and code inspection for the code.

Q. write a note on Refactoring APIs?

Refactoring REST APIs


Applies to ReadyAPI 3.43.1, last modified on February 09, 2023
If your web service is updated, you may need to change test cases and requests in ReadyAPI. ReadyAPI
offers the Refactor Definition command that simplifies this task. The command invokes a dialog box.
Use it to set a correspondence between existing and new resources, methods and requests, as well as
their parameters. Then, ReadyAPI will automatically update the requests and test steps in your project
so that they match the updated specification.
Note: If you do not have a WADL or Swagger/OpenAPI definition for your API (for example, if you
created a project from an endpoint), you will not be able to perform REST refactoring.
To use refactoring, you need the ReadyAPI Test license.
1. Start refactoring
1. Switch to Projects.
2. Do any of the following:
 Right-click your web service in the Navigator panel and select Refactor Definition from
the context menu:

3. – or –
 Select your web service in the Navigator panel and click Refactor on the toolbar:

Click the image to enlarge it.


4. – or –
 Select your web service in the Navigator panel and choose API > Refactor
Definition from the main menu:

Page 36 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

The Refactor Definition dialog will appear.


2. Load the updated definition
Use the Refactor Definition dialog to select the update definition to be used during refactoring. The
OpenAPI, Swagger, and WADL formats are allowed:

Click the image to enlarge it.


1. Enter the definition URL or file name in the Definition URL edit box.
2. Use the Definition Format settings to specify the format of the definition you are loading.
3. Select Create New Requests to create new requests for any new methods.
4. If the definition file specifies multiple services, select the one you need:

ReadyAPI will load and analyze the new definition. In the subsequent dialog, set a correspondence
between old and new operations.
3. Refactor definition
In the Refactoring REST Definitions dialog, specify which existing resources, methods and requests
match new ones:

Page 37 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

The dialog displays old items (resources, methods or requests) on the left and new items on the right.
ReadyAPI automatically matches the old items with the new ones. The old items that do not match the
new ones appear in red, while the new items that do not match the existing ones appear in blue.
Match existing resources, methods and requests with new ones in the following way:
 To indicate that an existing resource, method or request matches a new one, you connect them.
To do that, select an item in one panel, then select the matching item in the opposite panel and
click Connect:

 If the connected resource, method or request does not match the new one, disconnect them. To
do that, select an item in one of the panels (ReadyAPI will select the connected item in the
opposite panel automatically) and click Disconnect:

Page 38 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

Click the image to enlarge it.


When you click Next, ReadyAPI will do the following:
 If some existing resource, or its method, or a request matches the new resource, method or
request (that is, if the dialog shows a thin grey line between them automatically, or if you’ve
connected them manually in the dialog), then ReadyAPI will update existing items with the new
item data. At that, existing child methods and requests that don’t have new matching items will
not be changed. Also, ReadyAPI will add new methods and requests to the existing resource.
 If neither existing resource, nor its methods and requests match any new resource, method or
request, the existing item(s) are deleted.
 If a new resource and its methods and requests don’t match any existing item, ReadyAPI will
add these new items to the service definition stored in your project.
After you match all the needed items, click Next.
4. Refactor properties
ReadyAPI displays the Refactoring REST Definitions dialog:

Click the image to enlarge it.


The dialog shows the differences between the current and new versions of the linked items. Review the
suggested changes and adjust the final variant, if needed.
For linked methods, specify how ReadyAPI should treat representations. Select Overwrite to replace
representations with the updated versions, or select Ignore to keep the current representations.
If a parameter is absent in the new definition, select what ReadyAPI should do: remove the parameter or
link it with one of the new parameters. In the latter case, ReadyAPI will replace the absent parameter
with the linked one. In order not to lose the current value of the parameter, make sure to select the
Keep existing value option in the subsequent Parameters Refactoring dialog.

Page 39 of 279
www.profajaypashankar.com
SYCS ADVANCED APPLICATION DEVELOPMENT Q&A NOTES: BY.PROF.AJAY PASHANKAR

You might also like