0% found this document useful (0 votes)
22 views29 pages

Unit 4 PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views29 pages

Unit 4 PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Function Sequence:

JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.
This example will end up displaying "Goodbye":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Function Sequence</h2>
<p>JavaScript functions are executed in the sequence they are called.</p>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();
</script>
</body>
</html>

This example will end up displaying "Hello":


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Function Sequence</h2>
<p>JavaScript functions are executed in the sequence they are called.</p>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}

1
mySecond();
myFirst();
</script>
</body>
</html>

Sequence Control: Example1


Sometimes you would like to have better control over when to execute a function. Suppose you want to do a calculation
and then display the result.
You could call a calculator function (myCalculator), save the result and then call another function (myDisplayer) to
display the result:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Do a calculation and then display the result.</p>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
sum = num1 + num2;
return sum;
}
result = myCalculator(5, 5);
myDisplayer(result);
</script>
</body>
</html>

Sequence Control: Example2


Or, you could call a calculator function (myCalculator) and let the calculator function call the display function
(myDisplayer):
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Callbacks</h2>
<p>Do a calculation and then display the result.</p>

2
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
sum = num1 + num2;
myDisplayer(sum);
}

myCalculator(5, 5);
</script>
</body>
</html>

The problem with the first example above, is that you have to call two functions to display the result.
The problem with the second example, is that you cannot prevent the calculator function from displaying the result.
Now it is time to bring in a callback.
JavaScript Callbacks
A callback is a function passed as an argument to another function.
Using a callback, you could call the calculator function (myCalculator) with a callback and let the calculator function run
the callback after the calculation is finished:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Callbacks</h2>
<p>Do a calculation and then display the result.</p>
<p id="demo"></p>
<script>
function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}
function myCalculator(num1, num2, myCallback) {
sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
</script>
</body>
</html>

3
In the example above, myDisplayer is the name of a function.
It is passed to myCalculator() as an argument.

Asynchronous Javascript:
In the real world, callbacks are most often used with asynchronous functions.
A typical example is JavaScript setTimeout().

Waiting for a Timeout


When using the JavaScript function setTimeout(), you can specify a callback function to be executed on time-out:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Callback</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = “BMSCE !!";
}
</script>
</body>
</html>

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like
waiting for a file to load).
In the example above, myFunction is used as a callback.
myFunction is passed to setTimeout() as an argument.
3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.
In this example, function(){ myFunction(“BMS College!!!"); } is used as a callback. It is a complete function.
The complete function is passed to setTimeout() as an argument.
Instead of passing the name of a function as an argument to another function, you can always pass a whole function
instead:
<!DOCTYPE html>
<html>
<body>
4
<h2>JavaScript SetTimeout()</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
setTimeout(function() { myFunction(“BMS College !!!"); }, 3000);

function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
</script>
</body>
</html>

Waiting for Intervals:


When using the JavaScript function setInterval(), you can specify a callback function to be executed for each interval:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript setInterval()</h2>
<p>Using setInterval() to display the time every second (1000 milliseconds).</p>
<h1 id="demo"></h1>
<script>
setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();
document.getElementById("demo").innerHTML=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}
</script>
</body>
</html>

In the example above, myFunction is used as a callback.


myFunction is passed to setInterval() as an argument.
1000 is the number of milliseconds between intervals, so myFunction() will be called every second.
5
Note: When you pass a function as an argument, remember not to use parenthesis.
Example:
In this example, (x) => x >= 0 is a callback function.
It is passed to removeNeg() as an argument.

<!DOCTYPE html>
<html>
<body style="text-align: center">
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<p id="demo"></p>
<script>
// Create an Array
const myNumbers = [4, 1, -20, -7, 5, 9, -6];
// Call removeNeg with a Callback
const posNumbers = removeNeg(myNumbers, (x) => x >= 0);
// Display Result
document.getElementById("demo").innerHTML = posNumbers;
// Remove negative numbers
function removeNeg(numbers, callback) {
const myArray = [];
for (const x of numbers) {
if (callback(x)) {
myArray.push(x);
}
}
return myArray;
}
</script>
</body>
</html>

 JavaScript is an asynchronous language, which means that it can handle multiple tasks
simultaneously. Callbacks are a fundamental aspect of JavaScript, as they allow you to run code after
an asynchronous operation has been completed.
 A callback is a function that is passed as an argument to another function, and is called after the main
function has finished its execution. The main function is called with a callback function as its argument,
and when the main function is finished, it calls the callback function to provide a result. Callbacks allow
you to handle the results of an asynchronous operation in a non-blocking manner, which means that
the program can continue to run while the operation is being executed.

6
 Asynchronous operations are operations that take a significant amount of time to complete, such as
network requests, file I/O, and database queries. If these operations were executed synchronously, the
program would freeze and wait for the operation to complete before continuing. This can lead to a
poor user experience, as the program would appear unresponsive.
 Callbacks allow you to continue executing code while the operation is being executed in the
background. Once the operation has completed, the callback function is called with the result of the
operation. This way, you can ensure that the program remains responsive and the user experience is
not impacted.
 Real-Life Examples:
o Loading images on a website: When you load a website, images can take a while to load,
especially if they’re large. If images were loaded synchronously, the website would freeze and
wait for each image to load before continuing. With callbacks, you can load the images
asynchronously, which means that the website continues to load while the images are being
loaded in the background.
o Handling form submissions: When a user submits a form, it takes time to process the data and
send it to the server. If the form submission was executed synchronously, the user would have
to wait for the data to be processed and sent before the form can be submitted. With callbacks,
you can handle the form submission asynchronously, which means that the user can continue
to interact with the form while the data is being processed and sent in the background

Eg1:
function mainFunction(callback) {
console.log("Performing operation...");
// Use setTimeout to simulate an asynchronous operation
setTimeout(function() {callback("Operation complete");}, 1000);}

// Define the callback function


function callbackFunction(result) {
console.log("Result: " + result);
}

// Call the main function with the callback function


mainFunction(callbackFunction);

 Define a mainFunction that takes a callback as an argument.


 The mainFunction uses setTimeout to simulate an asynchronous operation. The setTimeout function takes two
arguments: a callback function and a delay time in milliseconds.
 The setTimeout function calls the callback function with the result of the operation after the specified delay
time.
 Then define a callbackFunction that logs the result of the operation.
 Finally, call the mainFunction with the callbackFunction as its argument.

7
Eg2:
// Define an array of numbers
var numbers = [1, 2, 3, 4, 5];

// Define the main function


function mainFunction(callback) {
console.log("Performing operation...");
// Use Array.forEach to loop through the array of numbers
numbers.forEach(callback);
}
// Define the callback function
function callbackFunction(number) {
console.log("Result: " + number);
}
// Call the main function with the callback function
mainFunction(callbackFunction);

 First define an array of numbers numbers.


 Then define a mainFunction that takes a callback as an argument.
 The mainFunction uses Array.forEach to loop through the numbers array and call the callback function for each
element in the array.
 Then define a callbackFunction that logs each number in the numbers array.
 Finally, call the mainFunction with the callbackFunction as its argument.

Eg3:
// program that shows the delay in execution
function greet() {
console.log('Hello world');
}
function sayName(name) {
console.log('Hello' + ' ' + name);
}
// calling the function
setTimeout(greet, 2000);
sayName('John');

8
The setTimeout() method executes a block of code after the specified time.
Here, the greet() function is called after 2000 milliseconds (2 seconds). During this wait, the sayName('John'); is
executed. That is why Hello John is printed before Hello world. The above code is executed asynchronously (the second
function; sayName() does not wait for the first function; greet() to complete).

Arrow function
Arrow function {()=>} is concise way of writing JavaScript functions in shorter way. They make our code more structured
and readable.

let func = (arg1, arg2, ..., argN) => expression;


This creates a function func that accepts arguments arg1..argN, then evaluates the expression on the right side with
their use and returns its result.

let sum = (a, b) => a + b;


alert( sum(1, 2) ); // 3

Example:

O/p:

9
Arrow functions allow us to write shorter function syntax:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows the syntax of an Arrow Function, and how to use it.</p>
<p id="demo"></p>
<script>
myFunction = (a, b) => a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
</script>
</body>
</html>

10
It gets shorter! If the function has only one statement and the statement returns a value, you can remove the
brackets and the return keyword.

Arrow Functions Return Value by Default:


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows an Arrow Function without the brackets or the return keyword.</p>
<p id="demo"></p>
<script>
var hello;
hello = () => "Hello World!";
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>

If you have parameters, you pass them inside the parentheses:


Arrow Function With Parameters:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows an Arrow Function with a parameter.</p>
<p id="demo"></p>
<script>
var hello;
hello = (val) => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>

In fact, if you have only one parameter, you can skip the parentheses as well:
Arrow Function Without Parentheses:
<!DOCTYPE html>
11
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows that if you have only one parameter in an Arrow Function, you can skip the parentheses.</p>
<p id="demo"></p>
<script>
var hello;
hello = val => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>

OR
o/p:

OR

 We don’t need function.


 As only one line in function body, we don’t need parenthesis.
 As only one value, it is returned. We don’t need return statement also.

Convert these 4 functions into Arrow functions:

12
13
o/p:

o/p:

o/p:

o/p:
Arrow Function without Parameters
const gfg = () => {
console.log( "Hello World!" );
}
gfg();

14
Arrow Function with Parameters
const gfg = ( x, y, z ) => {
console.log( x + y + z )
}
gfg( 10, 20, 30 );

Arrow Function with Default Parameters


const gfg = ( x, y, z = 30 ) => {
console.log( x + " " + y + " " + z);
}
gfg( 10, 20 );

Example:

Function Arrow function


function ask(question, yes, no) { ask(
if (confirm(question)) yes(); "Do you agree?",
else no(); function() { alert("You agreed."); },
} function() { alert("You canceled the execution."); }
);
let sum = (a, b) => a + b; let sum = function(a, b) {
alert( sum(1, 2) ); // 3 return a + b;
};
alert( sum(1, 2) ); // 3

Advantages of Arrow Functions


 Arrow functions reduce the size of the code.
 The return statement and function brackets are optional for single-line functions.
 It increases the readability of the code.
 Arrow functions provide a lexical this binding. It means, they inherit the value of “this” from the
enclosing scope. This feature can be advantageous when dealing with event listeners or callback
functions where the value of “this” can be uncertain.
Limitations of Arrow Functions
 Arrow functions do not have the prototype property.
 Arrow functions cannot be used with the new keyword.

15
 Arrow functions cannot be used as constructors.
 These functions are anonymous and it is hard to debug the code.
 Arrow functions cannot be used as generator functions that use the yield keyword to return multiple
values over time.

JSON

The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for
reading and generating JSON data can be written in any programming language.

JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
The JSON Format Evaluates to JavaScript Objects:
The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

JSON Syntax Rules:


Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays

16
Note: JSON names require double quotes. JavaScript names do not.

JSON Values
In JSON, values must be one of the following data types:
 a string
 a number
 an object
 an array
 a boolean
 null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
 a function
 a date
 undefined

JSON Arrays:
JavaScript Array and JSON Array are nearly the same. String, array, boolean, integer, object, null, and boolean values can
all be stored in JSON arrays. Values are separated by commas in the JSON array. The [] operator can be used to access
array elements.

JSON arrays are written inside square brackets.


Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).

JSON Arrays Example Program:


<!DOCTYPE html>
<html>
<body>
<p id="para"></p>
<script>
var jsonStringArray = {
// Assigned a JSON array of strings to the key "students".
"students": ["Ram", "Shyam", "Raksha", "Akshay", "Prashant", "Varun“, ”Manju”],
17
};
// It returned an array. Then we accessed
// the first index of the array (which is "Ram") using [] syntax.
var x = jsonStringArray.students[0];
// Set the inner HTML of "para" paragraph to the value of variable "x".
document.getElementById("para").innerHTML = x;
</script>
</body>
</html>
o/p:

Converting a JSON Text to a JavaScript Object


A common use of JSON is to read data from a web server, and display the data in a web page.
For simplicity, this can be demonstrated using a string as input.
 First, create a JavaScript string containing JSON syntax:

let text = '{ "employees" : [' +


'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

 Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
const obj = JSON.parse(text);

 Finally, use the new JavaScript object in your page.


document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName;

Example:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
const obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
</body>
</html>

18
Example:
// JSON object
const data = {
"name": "John",
"age": 22,
"hobby": {
"reading" : true,
"gaming" : false,
"sport" : "football"
},
"class" : ["JavaScript", "HTML", "CSS"]
}
// accessing JSON object
console.log(data.name); // John
console.log(data.hobby); // { gaming: false, reading: true, sport: "football"}
console.log(data.hobby.sport); // football
console.log(data.class[1]); // HTML

// JSON object // json object // JavaScript object


const data = { const jsonData = '{"name": "John", const jsonData = { "name": "John",
"name": "John", "age": 22 }'; "age": 22 };
"age": 22
} // converting to JavaScript object // converting to JSON
// accessing JSON object const obj = JSON.parse(jsonData); const obj = JSON.stringify(jsonData);
console.log(data["name"]); // John // accessing the data // accessing the data
console.log(obj.name); // John console.log(obj);
// "{"name":"John","age":22}"

Example: Convert a string into a date object


<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a date object.</h2>
<p id="demo"></p>
<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
19
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
</body>
</html>

Example: Convert a string into a function


<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a function.</h2>
<p id="demo"></p>
<script>
const text = '{"name":"John", "age":"function() {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();
</script>
</body>
</html>

Example: Parsing a JSON Array


<!DOCTYPE html>
<html>
<body>
<h2>Parsing a JSON Array.</h2>
<p>Data written as an JSON array will be parsed into a JavaScript array.</p>
<p id="demo"></p>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>
</body>
</html>

20
Example: Convert a JSON Text to a JavaScript Object

let text = '{"model":[' +


'{"carName":"Baleno","brandName":"Maruti"},' +
'{"carName":"Aura","brandName":"Hyndai"},' +
'{"carName":"Nexon","brandName":"Tata"}]}';

const cars = JSON.parse(text);


console.log("The car name is: " + cars.model[2].carName + " of brand: " +
cars.model[2].brandName);

Example: Looping Object Properties


<!DOCTYPE html>
<html>
<body>
<h2>Looping Object Properties</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Example: Looping JavaScript Object Values


<!DOCTYPE html>
<html>
<body>
<h2>Looping JavaScript Object Values</h2>
<p id="demo"></p>
<script>
21
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += myObj[x] + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Example: Accessing Object Values

<!DOCTYPE html> <!DOCTYPE html>


<html> <html>
<body> <body>
<h2>Access a JavaScript Object</h2> <h2>Access a JavaScript Object</h2>
<p id="demo"></p> <p id="demo"></p>
<script> <script>
const myJSON = '{"name":"John", "age":30, "car":null}'; const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON); const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML =
myObj.name; myObj["name"];
</script> </script>
</body> </body>
</html> </html>

HTTP headers
HTTP headers contain metadata in key-value pairs that are sent along with HTTP requests and responses. They can be
used to define caching behavior, facilitate authentication, and manage session state. HTTP headers help the API client
and server communicate more effectively—and enable developers to optimize and customize the API’s behavior.

Most common HTTP headers


HTTP headers play a crucial role in server and client behavior throughout the request and response cycle. Request
headers are sent by the client to the server and contain information and instructions related to the requested resource,
while response headers are sent by the server to the client and provide metadata, instructions, and additional
information about the response itself.
Some of most commonly used request headers are as given below:
 Accept
 User-Agent
22
 Authorization
 Content-type
 Cookie

The most common response headers are:


 Content-type
 Cache-control
 Server
 Set-cookie
 Content-length

 Accept
The Accept header defines the media types that the client is able to accept from the server.
 User-Agent
The User-Agent header identifies the web browser or client application that is making the request, which
enables the server to tailor its response to the client.
 Authorization
The Authorization header is used to send the client’s credentials to the server when the client is attempting to
access a protected resource.
 Content-Type
The Content-Type header identifies the media type of the content in the request body.
 Cookie
The client can use the Cookie header to send previously stored cookies back to the server.

 Content-Type
The Content-Type response header is the counterpart of the Content-Type request header, as it indicates the
type of data that the server is sending to the client. The header value typically includes the media type (such as
text/html, application/json, image/jpeg, and audio/mp3), as well as any optional parameters.
 Cache-Control
The Cache-Control header controls caching behavior in the client’s browser or intermediate caches. It defines
how the response can be cached, when it expires, and how it should be revalidated.
 Server
The Server header includes the name and version of the server software that generated the response, as well as
information about the server’s technology stack.
 Set-Cookie
The Set-Cookie header instructs the client to store a cookie with the specified name, value, and additional
attributes, such as expiration, domain, path, and security flags.
 Content-Length
The Content-Length header, which specifies the size of the response body in bytes, can help the client anticipate
how much data it is going to receive.

How does Postman make it easier to work with HTTP headers?


The Postman API Platform is the gold standard for all API-related work, and it includes several features that
streamline the process of working with HTTP request and response headers. With Postman, you can:

23
 Set request headers from an intuitive user interface: Users can easily set and adjust headers from within the
Headers tab of a request. Postman will also prompt you with common headers to help you automatically
complete your setup.
 Save groups of commonly used request headers: Header presets allow users to keep commonly used headers
together, which can then be reused in other requests.
 Leverage auto-generated request headers: Postman will automatically add certain headers to your request
according to its configuration. You can hover over any of these headers for additional information about why it
was included, as well as instructions for how to deactivate or override it.
 View, edit, and capture cookies: Postman’s cookie manager enables users to easily keep track of the cookies
that are associated with various domains. Users can also capture cookies with the Postman proxy or Postman
Interceptor—and then use the cookies in the cookie jar when sending requests.
 Safely store credentials: Users can set credentials in the Authorization tab—and add these credentials to the
Authorization request header. Postman provides support for several types of authorization, including API keys,
OAuth 2.0, and JWT.
 View response headers: All response headers are displayed as key-value pairs under the Headers tab of the
response. Users can hover over any header’s information icon to learn more about it.

Configure headers for API requests in Postman


Configure request headers:
You can configure headers in the Headers tab of your request. Enter any key-value pairs you need and Postman will send
them along with your request. As you enter text, Postman prompts you with common options you can use to
autocomplete your setup, such as Content-Type.
When you're done configuring headers, select Send to send the request.

Header presets:
You can save commonly used headers together in a header preset. In the Headers tab of your request, select the Presets
dropdown list and choose Manage Presets. Select Add Header Preset to add a new preset, and enter a name for the
preset. Enter key-value pairs, then select Add.
You can select your preset in the Presets dropdown list. Selecting the preset will autopopulate the fields in your request
headers.

Autogenerated headers:
24
Postman will automatically add certain headers to your requests based on your request selections and settings. Select
hidden at the top of your request's Headers tab for information about what Postman will send with your request.

Hover over a header to view details about it. Postman will indicate why the header has been added. The details will also
indicate how to deactivate or override a header value if you need to.

Postman – Working, HTTP Request & Responses


API is a defined set of rules with some defined methods of communication. With the help of API, software components
can interact with each other.
Eg: payment gateway API
Implementing a quality API is really important to ensure fast development without compromising on the code quality.
The best and popular tool for API testing among developers is Postman.
In API testing we test the collection of APIs, and we check that whether your application fulfills the expectations of
functionality, reliability, performance, and security. Also, we check that whether it returns the correct response or not.
In API testing we check that whether the output is well-structured and useful for some other application or not.
Depending on the input parameter we check the response, and we determine the time API is taking to extract the data
and authorize the data to it.

Postman is a popular tool used by developers for testing APIs. When working with APIs in Postman, understanding
requests and responses is fundamental.

Request:
A request is an action you make to an API endpoint. It could be a GET request to fetch data, a POST request to submit
data, a PUT request to update data, or a DELETE request to remove data.
In Postman, you create requests by specifying the HTTP method (GET, POST, PUT, DELETE, etc.), the URL of the API
endpoint, request headers (optional), request body (optional, typically used with POST and PUT requests to send data),
and any query parameters (optional, for filtering or pagination).
After configuring the request, you can send it to the API server by clicking the "Send" button. Postman then sends the
request to the specified endpoint and waits for a response.

Response:
A response is the result returned by the API server after processing your request. It contains information such as status
code, headers, and optionally, a response body.

25
The status code indicates the success or failure of the request. For example, a status code in the 200 range (e.g., 200 OK)
typically indicates success, while a status code in the 400 or 500 range indicates an error.
Response headers provide metadata about the response, such as content type, server type, and caching directives.
The response body (if present) contains the actual data returned by the API server. This could be JSON, XML, HTML, or
any other format depending on the API.
In Postman, once the request is sent, you can view the response in the "Response" pane. Postman displays the status
code, headers, and response body (if available). This allows you to inspect the data returned by the API and verify if it
meets your expectations.

How Postman Works?


Postman sends the request to the webserver and then the server sends the response back to it. A user has to set all the
headers and cookies API expects to check the response.
This tool provides a collection of API calls, and you need to follow these API calls for testing APIs of the application. You
will find a dropdown list with multiple methods.
You can select one of the methods from the given dropdown list. You will also have to include more information
depending on the API call. This information are set as Authorization, Header, or body information. You just need to
select one of the methods and send the request and get the response back.

Collections are a bundle of requests. To create a collection, you can add an API call in the collection. You can reuse it in
your application. A lot of organizations offer collections. You can import this in your postman and test it. If you have
created a collection, you can export it or if you want the collection of others, you can import it.

API call mainly uses:


1. HTTP Request
You make HTTP calls sending the HTTP Request. In HTTP request method includes Request Method, Request URL,
Request Headers, Request Body, Pre-request Script, and Tests.
Request Methods: You will find several types of Request methods in POSTMAN. Depending on your requirements or test
you can choose one of them. Mainly you will be using four request methods in your application. These methods are
given below…
 GET Request: To retrieve or fetch data
 POST Request: To create and update data
 PUT Request; To update data
 DELETE Request: For deleting data

Request URL: You will find a long-width bar in Postman where you will have to enter the URL to make the HTTP request.
Request Headers: In the request header, you enter the key value of the application. The two main key values are given
below.
Content-Type: The format of data is specified by Content-Type. Mainly developers use JSON format in the content type.
Authorization: This information is included to identify the requester.
Request Body: In Postman, you will get the tab of Body where you can mention some specific information that needs to
be sent with the request. You will get the option to send the data either in raw, binary, or any other form. Most of the
time you will select raw form. You will also get the option of Pre-request scripts. This gets executed before a request is
sent. In Postman, you are also allowed to write and run the test for each request. You can use JavaScript language for
this.

2. HTTP Response

26
Once you send the request to Postman, you get the response back from the API that contains Body, Cookies, Headers,
Tests, Status Code, and API Response time. Body and Header get organized in different tabs. Status code gets displayed
in another tab with the time taken to complete the API call. Some important status codes are given below to verify the
response.

200– For successful request.


201– For successful request and data was created
204– For Empty Response
400– For Bad Request.
401– For Unauthorized access. Authentication failed or the user does not have permission for the requested operation.
403– For Forbidden, Access Denied
404– For data not found.
405– For method not allowed or requested method is not supported.
500– Internal server error.
503– For Service unavailable

HTTP status codes


HTTP status codes are three-digit codes that indicate the outcome of an API request. They are included in the API’s
response to the API client and they include important information that helps the client know how to proceed.
HTTP status codes are essential to the HTTP protocol, which defines how data is transferred between clients and servers
on the internet. Anyone who works with web-based technologies should have a solid understanding of these codes, as
they provide valuable insight that can be used to troubleshoot issues and improve the user experience.

Different types of HTTP status codes


HTTP status codes are grouped into five classes, each beginning with a number that represents the type of response. The
classes are:
1xx informational responses
2xx success responses
3xx redirection responses
4xx client error responses
5xx server error responses

27
28
29

You might also like