You are on page 1of 173

API TESTING – POSTMAN TOOL

By
G.Kiran
WHAT IS API

2
WHAT IS API
Have you ever heard the word “API,” and wondered exactly what it is? Do you have a
vague idea of what you might do with an API?

API stands for Application Programming Interface. In basic terms, APIs are a set of
functions and procedures that allow for the creation of applications that access data
and features of other applications, services, or operating systems.

Good APIs make it easier to develop a computer program by providing all the building
blocks, which are then put together by the programmer.”

What is an API?

Let’s get down to it go deeper and pick apart what an API is, what makes it different, why
is it so popular, and what are the different challenges? The API is not the database or
even the server, it is the code that governs the access point(s) for the server.

3
WHAT IS API
• API is an acronym for APPLICATION PROGRAMMING INTERFACE

• API is application to application interface

• API is not at user interface level

• API makes applications talk to each other without the user intervention/knowledge

• API are executed automatically by function calls in the program

• API enables communication and data exchange between 2 separate software


systems

• API testing won't concentrate on the look and feel of an application

4
API – A REAL WORLD EXAMPLE
A real-world example is buying movie tickets online. You go to the movie site; you enter
your movie, name and credit card information, and lo-and-behold, you print out your
tickets.

But what’s going on between entering your information to receiving your ticket? APIs,
that’s what! They are collaborating behind the scenes with other applications.

How is this possible you ask? This type of integration is called “seamless” because you
never have a clue when a software role is passed from one application to another.

5
WHAT IS API
Applications often have three layers:

• Presentation (UI) layer


• Service (API) layer
• Data layer

The API layer contains the business logic of an application – the rules of how users can
interact with services, data, or functions of the app. Since the API or service layer directly
touches both the data layer and the presentation layer, it presents the sweet spot of
continuous testing for Testing and Development teams.

API testing involves testing the application programming interfaces (APIs) for functionality,
security, Performance. Since APIs lack a GUI, API testing is performed at the Service layer.

6
WHAT IS API
• APIs are used to integrate systems together. You can make data available for other
systems to access via API or accept data from other systems. This is how different
devices and applications talk to each other and share information.

• Successful companies like Facebook, YouTube, and Twitter use APIs so that their
application can communicate with third party programs. Usually API work similarly to
the way any website works. A request is made from the client to the server and we get
the response over the http protocol.

• An API is the messenger that takes your request and tells the systems what to do and
then returns the response back to you.

7
WHAT IS API WORKFLOW

8
APIs vs WEBSERVICES

9
HISTORY OF APIs – SOAP XML vs REST JSON API vs RPC

10
HISTORY OF APIs – SOAP XML vs REST JSON API vs RPC
In 2000, Roy Fielding’s started what we know as modern web APIs thanks to his
dissertation “Architectural Styles and the Design of Network-based Software
Architectures,” other forms came later.

All of this is not new. During the 2000s, we had SOAP Services which were leveraged for
some of the same use cases.

REST provides a lighter-weight alternative. Many developers found SOAP cumbersome


and hard to use. REST is easy to understand, and it’s simple to write and document.

This ease of use also makes it easy for other developers to understand and write
applications.

11
HISTORY OF APIs – SOAP XML vs REST JSON API vs RPC
REST also makes efficient use of bandwidth, as it’s much less verbose than SOAP.

REST supports many data formats, but the predominant use of JSON means better support
for browser clients.

JSON sets a standardized method for consuming API payloads so that you can take
advantage of its connection to JavaScript and the browser. So, what is JSON and why do
we use it?

JSON stands for JavaScript Object Notation and is a way of representing data that looks
like JavaScript objects.

Let’s look at a very typical JavaScript Object for a Restaurant on Yelp, which might look a
bit like this:

12
HISTORY OF APIs – SOAP XML vs REST JSON API vs RPC
Neat. This is fairly easy to read — our data is stored as key/value pairs.

This means that we can see the key on the left, and the value on the right. The key stays
the same for each Restaurant object, but the value would be different.
A different Restaurant would have a different address, but its properties would be the
same — it would always have a name, address, zip, phone, and email.

So JSON is everywhere in the modern web, mobile, and IoT applications. It’s readable, it’s
lightweight, and it works super well with applications written in JavaScript, as
it is JavaScript.

But is also comparatively easy to get applications written in other languages to read it
and generate it as well — including Java.

This means that an API that returns JSON can be accessed by an application written in
Java, Ruby, Python, JS, PHP, and many more.

This makes an API developer-friendly, highly scalable, and platform-independent.

So, with developer buy-in, APIs started exploding in importance and organizations started
leveraging them with great success.

So much so that APIs became a strategic necessity for businesses.

Here’s an example of what happens in an internet minute. All these companies leverage
APIs for their interactions. Who Creates these Web, Mobile, IoT-Based Public APIs?
13
HISTORY OF APIs – SOAP XML vs REST JSON API vs RPC

Since this also came along with Web, Mobile, and IoT Innovations.
Especially with Public APIs. Large tech companies, especially social media companies, frequently
make their aggregate data available to the public.
Not just modern or social media companies…

APIs are also maintained by government organizations, banks, healthcare organizations,


conferences, publishing houses, software start ups, fan groups, eSports leagues, and even
individuals, to share anything from social media content to trivia questions, rankings, maps, song
lyrics, recipes, parts lists, and more.

APIs are everywhere!

APIs have grown enormously popular in recent years with different types of APIs. As I mentioned
earlier, this is due to a couple of key changes in the industry.

1.First, the enormous growth of mobile apps that frequently talk to back ends over the web.

2.Second, the rapidly emerging “Internet of Things” (IoT) promises to bring connectivity to common
devices we use in our everyday lives.

14
TYPES OF APIs

15
TYPES OF APIs

16
TYPES OF APIs
There isn’t just one type of API (Application Programming Interface) but actually, there are four
main types of APIs:

•Open APIs, aka Public APIs, are publicly available to developers and other users with minimal
restriction. They may require registration, use of an API Key or OAuth, or maybe completely open.
They focus on external users, to access data or services.

•Partner APIs are APIs exposed by/to the strategic business partners. They are not available publicly
and need specific entitlement to access them. Like open APIs, partner APIs are the tip of the
iceberg because they are the most visible ones and are used to communicate beyond the
boundaries of the company. They are usually exposed to a public API developer portal that
developers can access in self-service mode. While open APIs are completely open, there is an on-
boarding process with a specific validation workflow to get access to partner APIs.

•Internal APIs, aka private APIs, are hidden from external users and only exposed by internal
systems. Internal APIs are not meant for consumption outside of the company but rather for use
across different internal development teams for better productivity and reuse of services. A good
governance process comprises exposing them to an internal API developer portal that connects to
the internal IAM systems to authenticate and allow users to access the right set of APIs.

•Composite APIs combine multiple data or service APIs. They are built using the API
orchestration capabilities of an API creation tool. They allow developers to access several
endpoints in one call. Composite APIs are useful, for example, in a microservices architecture
pattern where you need information from several services to perform a single task.

17
TYPES OF APIs

18
TYPES OF APIs

Types of APIs

There are four main APIs that are often used (of course there are more):

1.Open APIs which are publicly available for everyone to utilize.


2.Partner APIs which are custom designed by enterprises to offer access to business partners to
reserve or buy specific items, such as tickets or vouchers.
3.Private APIs (or Internal) are not for public consumption but used internally.
4.Composite APIs: This combines diverse data and service APIs. Its foremost abilities speed up the
course of implementation, as well as advance the functioning of viewers within the web borders.

Key takeaways

It’s important to remember key takeaways for APIs are as follows:

•APIs are prevailing tools that are used to fast-track your business.
•APIs make connections and product shopping possible at a rapid speed such as booking a hotel
or ordering a movie ticket.
•APIs provide key insights into real-time possibilities for analytics delivery on the spot.
•APIs give the developer the ability to make an API call or “request” to obtain information.

19
TYPES OF API ARCHITECTURE

20
TYPES OF API PROTOCOLS

Types of API Protocols

To leverage these different types of APIs, we must follow certain protocols. A protocol
provides defined rules for API calls. It specifies the accepted data types and commands.
Let’s look at the major types of protocols for APIs:

1.REST

REST (short for Representational State Transfer) is a web services API. REST APIs are a key
part of modern web applications, including Netflix, Uber, Amazon, and many others. For
an API to be RESTful, it must adhere to the following rules:

•Stateless—A REST API is stateless in nature, Client-Server Architecture

•Uniform Interface—A client and server should communicate with one another via HTTP
(HyperText Transfer Protocol) using URIs (Unique Resource Identifiers), CRUD (Create,
Read, Update, Delete), and JSON (JavaScript Object Notation) conventions.

•Client-Server—The client and server should be independent of each other. The changes
you make on the server shouldn’t affect the client and vice versa.

•Cache—The client should cache the responses as this improves the user experience by
making them faster and more efficient.

•Layered—The API should support a layered architecture, with each layer contributing to 21
a clear hierarchy. Each layer should be loosely coupled and allow for encapsulation.
RESTful APIs

•REST stands for Representational State Transfer.

•REST is an architectural style.

•Web services following REST Architectural style are called RESTful Web services

•REST message request is processed faster as compared to SOAP.

•REST supports data formats like plain text, XML, HTML, JSON, etc.

•REST is easier to implement.

•REST requires less bandwidth and resources.

•REST Message is enclosed in HTTP and uses HTTP Method and URI (Uniform
Resource Identifier)

•It uses web caching mechanism i.e. data can be cached at the client.

•REST is commonly used in social media, web chat and mobile services.

22
REST API
• REST is an acronym for REPRESENTATIONAL STATE TRANSFER

• REST is an architectural style and follows HTTP protocol

• REST API is a set of functions to which the user executes requests and receives responses

• REST API interaction is achieved via HTTP protocol

• REST API interaction between 2 different applications is achieved through an established


network such as internet

• REST involves using HTTP methods to send and receive messages and does not require a
strict message definition unlike Web Services

• REST messages often take the form of XML, or Java Script Object Notation (JSON)

23
REST API

24
HTTP METHODS
• Below are the 4 commonly used HTTP methods in REST API calls:

• GET : Provides a read only access to a resource

• POST : Used to update an existing resource or create a new resource

• PUT : Used to update an existing resource

• DELETE : Used to remove an existing resource

25
HTTP METHODS
GET:

This HTTP method is used to read/retrieve resource representation only. It is called Safe
methods as it can not modify information. It should retrieve same information for multiple
identical requests until any other API has changed the state of resource. That’s why it is also
called as idempotent method. Response is returned in JSON/XML format.

Status Codes:

200 (OK) –> If GET API finds the requested resource.


404( Not Found) –> If GET API does not find the requested resource.
400 ( Bad Request) –> If GET request is not formed properly.

POST:

A HTTP POST method is used to create a new resource in collection of resources with a
request body passed as a JSON/XML. If resource is created successfully at the end point, it
returns a status code

Status Codes:

201( Created) (Not always) and returns response body.


It may return 200 (OK) and 204 (No Content) status code as well based on how it is created.

POST is not safe method as it is related to data creation. It is also not idempotent and
invoking two identical POST requests will result in two different resources containing the same
information with just different resource ids. 26
HTTP METHODS
PUT:

An HTTP PUT method is used to primarily update the resource information but it also can be
used to create a new resource (Depends on API development) if requested resource is not
available. If PUT request is made to update resource, it should return 200 (OK) and 204 (No
Content) status code. If PUT request is made to create a new resource, it must return a status
code 201( Created).

PUT is not a safe method as it performs data creation and modifications but it is idempotent
as if we hit the same request again, it operates on same existing resource. But note here that
a PUT request can be made as non-idempotent as well.

DELETE:

An HTTP DELETE method is used to delete an existing resource from collection of resources.
On successful deletion of resource, it returns 200 (OK) and 204 (No Content) status code. It
may return as 202 (Accepted) status code if request is queued.

It is not a safe method as it performs on modification of data. If we hit the same request
again after first hit, it will give you 404 ( Not Found) . So DELETE request are idempotent after
second call onward.

27
HTTP METHODS
PATCH:

An HTTP PATCH method is used to update information of resource partially. It is different from
PUT as PUT updates/replace complete information of resource while PATCH updates some
information of resource. It returns 200 (OK) and 204 (No Content) status code.

A PATCH method is not safe method as it operations on modification of data. It is also non-
idempotent but can be made idempotent.

HEAD:

An HTTP HEAD method is identical to GET method without response body. Instead of
response body or resource information, a GET request returns meta information/headers
contented in an HTTP GET method. This method can be used for obtaining meta information
about the entity implied by the request without transferring the entity-body itself.

OPTIONS:

An HTTP OPTIONS method which is used to get information about allowed operations on
given URI. It returns a response header named “Allow” with the list of available operation on
given URI.

28
HTTP SAFE METHODS & IDEMPOTENT METHODS

All HTTP methods can be categorised in two categories: Safe methods & Unsafe methods.
We know that all HTTP methods deal with resource. Some read the state of resource or some
create/update the state of resource.

If an HTTP method does not change/modify the resource information on the server side or
perform read only operation, is called a SAFE HTTP Method. The reason it is called as a safe
method as it does not alter resource information and prevents actual resource state.

GET, HEAD and OPTIONS HTTP methods are safe methods. This methods perform read only
operations. POST, PUT etc. are unsafe methods.

An HTTP method is called an idempotent method if multiple request to same method has the
same state of resource on the server as after first request (Conditional). In more easy word:
You hit a request, request performs some action on resource which may or may not change
state of resource. Now you hit the same request again, it will do the same action again.
Nothing new will happen.

29
HTTP METHODS - CLASSIFICATION

30
HTTP RESPONSE CODES
RESPONSE CODES: these are sent from server to the client, to tell the status of client
request ; Response codes are 100 - 599

100 - 199 ==> 1XX ==> INFORMATIONAL RESPONSE

200 - 299 ==> 2XX ==> SUCCESSFUL RESPONSE

300 - 399 ==> 3XX ==> REDIRECTIONAL RESPONSE

400 - 499 ==> 4XX ==> CLIENT SIDE ERROR

500 - 599 ==> 5XX ==> SERVER SIDE ERROR

Some of the most common HTTP response codes used with REST are as follows :

•200 (OK): This code indicates that the request was made successfully.
•201 (Created): This response code indicates that request was successful and a resource
was created. It is used to confirm success of a PUT or POST request.
•400 (Bad Request) : This code indicates that the data is in incorrect format.
•401 (Unauthorized) : This code indicates an authentication error.
•405 (Method Not Allowed) : This code indicates that HTTP method used is not supported
for this resource.
•409 (Conflict) : This code indicates that there is a conflict request to create the same
resource twice.
•404 (Not Found) :This code indicates that the required resource could not be found.
•500 (Internal Server Error) : This code indicates that there is some error on Server side. 31
HTTP RESPONSE CODES
During API TESTING, below response codes has these meanings:

2XX = test case passed

4XX = test case failed

5XX = test case failed

for more info, refer


https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

32
OTHER TYPES OF API PROTOCOLS

33
OTHER TYPES OF API PROTOCOLS

2.SOAP

SOAP (simple object access protocol) is a well-established protocol similar to REST in that
it’s a type of Web API.

SOAP has been leveraged since the late 1990s. SOAP was the first to standardize the way
applications should use network connections to manage services.

But SOAP came with strict rules, rigid standards were too heavy and, in some situations,
very resource intensive. Except for existing on-premise scenarios, most developers now
prefer developing in REST over SOAP.

3.RPC

An RPC is a remote procedural call protocol. They are the oldest and simplest types of
APIs. The goal of an RPC was for the client to execute code on a server. XML-RPC used
XML to encode its calls, while JSON-RPC used JSON for the encoding.
Both are simple protocols. Though similar to REST, there are a few key differences. RPC
APIs are very tightly coupled, so this makes it difficult to maintain or update them.
To make any changes, a new developer would have to go through various RPCs
documentation to understand how one change could affect the other.
APIs play a key role in the development of any application. And REST has become the
preferred standard for building applications that communicate over the network.
REST fully leverages all the standards that power the World Wide Web and is simpler than
traditional SOAP-based web services. Unlike RPC, it allows for a loosely coupled layered 34
architecture to maintain easily or update them.
SOAP APIs

•SOAP stands for Simple Object Access Protocol.

•SOAP is a protocol. It defines some standards that should be followed strictly.

•Web services following SOAP principles are called SOAP Web services

•SOAP message request is processed slower as compared to REST.

•SOAP supports only XML data format.

•SOAP is not very easy to implement so it is preferred less.

•SOAP requires more bandwidth and resources.

•SOAP Message contains Envelope, body and header.

•It does not use web caching mechanism.

•SOAP is commonly used in payment gateways, financial and


telecommunication services.

35
SOAP API
WSDL
• WSDL stands for Web Services Description Language
• WSDLs are an XML format that tells you how to access a web service.
• WSDL is used to describe web services
• WSDL is written in XML

SOAP
•SOAP stands for Simple Object Access Protocol. It helps in exchanging structured
information between computer networks.

•SOAP allows communication between different operating systems using XML.

SOAP Message Elements

1) SOAP Envelope – The SOAP Envelope is always the top element in the message.

2) Header – the Header is optional and is the first child element to appear after the
envelope. Headers can contain different types of application-specific information like
security authentication or session management info.

3) Body – Sometimes referred to as the payload, the Body contains the actual message that
shows the information for the recipient of the message.

36
API DATA COMMUNICATION

XML

•XML stands for extensible Markup Language


•It’s a mark-up language much like HTML
•XML was designed to store and transport data
•XML was designed to be self-descriptive
•It has sender information.
•It has receiver information
JSON
•It has a heading
•It has a message body.
JSON stands for JavaScript Object Notation and
was designed to be a lightweight data
interchange format.

JSON is definitely becoming more popular and is


now replacing XML in certain situations for API
data exchanging. The site www.json.org describes
how JSON is built on two structures:

1. “A collection of name/value pairs. In various


languages, this is realized as an object, record,
struct, dictionary, hash table, keyed list, or
associative array.

2. 2. “An ordered list of values. In most languages,


this is realized as an array, vector, list, or
37
sequence.”
REST API vs SOAP API

38
REST API vs SOAP API

39
REST API vs SOAP API

40
SAMPLE API SYNTAX & EXAMPLES

41
API SYNTAX

• Below is a generic API syntax:

• HTTP METHOD – PROTOCOL – BASE URL – END POINT – QUERY PARAMETERS – REQUEST
BODY – REQUEST HEADERS – REQUEST COOKIES – AUTHENTICATION

• The HTTP method can be GET, POST, PUT, PATCH, DELETE etc
• The Protocol can be HTTP, HTTPS

• http = HYPERTEXT TRANSFER PROTOCOL


• unsecured protocol [transfers the data from client to server in plain text]

• https = HYPERTEXT TRANSFER PROTOCOL with SECURITY


• secured protocol [transfers the data from client to server in encrypted text]

• to convert http to https, the developer uses any of the below 2 cryptographic
protocols:

• (i) SSL ==> SECURE SOCKETS LAYER [older protocol]


• (ii) TLS ==> TRANSPORT LAYER SECURITY [latest protocol]

• HTTP+SSL = HTTPS
• or
• HTTP+TLS = HTTPS
42
API SYNTAX

• Below is a generic API syntax:

• HTTP METHOD – PROTOCOL – BASE URL – END POINT – QUERY PARAMETERS – REQUEST
BODY – REQUEST HEADERS – REQUEST COOKIES – AUTHENTICATION

• HTTP METHOD: This tells the server 'what type of request' is being sent by the client

• GET ==> to retrieve the existing data from the server/database

• eg. GET https://www.bbc.com/news

• POST ==> to create new data on the server/database

• eg. Creating a new email account on gmail/fb/twitter/etc

• PUT ==> to replace/update existing data on the server/database

• eg. change password

• DELETE ==> to remove/delete existing data on the server/database

• eg. deleting your tweets/facebook posts/emails


• deactivating email accounts, social media accounts
43
API SYNTAX

• Below is a generic API syntax:

• HTTP METHOD – PROTOCOL – BASE URL – END POINT – QUERY PARAMETERS – REQUEST
BODY – REQUEST HEADERS – REQUEST COOKIES – AUTHENTICATION

• REQUEST HEADERS:

• these are additional meta data sent from the client to the server ; few sample request
headers are

• USER-AGENT: Windows 10 OS + 64 bit + Chrome + v89 + IP address @ 127.0.0.1

• ACCEPT: html ; text ; images/jpeg ; images/png ; json ; xml

• ACCEPT-LANG: EN-US ; EN-UK ; EN-CANADA ; Portuguese

• COOKIES: <cookie details>

• TRANSFER ENCODING: base64, gzip, deflate, br

44
API SYNTAX & API EXAMPLES WITH GET METHOD

• GET https://www.kiran.com/all-courses?courseName=APITesting

• http method = GET


• protocol = https
• base URL = www.kiran.com
• end point = all-courses
• query parameter : courseName=APITesting
• Key = courseName
• Value = APITesting

GET https://www.kiran.com/all-courses?courseName=APItesting&type=Postman

• http method = GET


• protocol = https
• base URL = www.kiran.com
• end point = all-courses
• query parameter 1: courseName
• query parameter 2: type
During API TESTING, when the response code from the server received is :

2XX ➔ the test case has passed


4XX ➔ the test case has failed due to client side issues
45
5XX ➔ the test case has failed due to server side issues
API SYNTAX & API EXAMPLES WITH POST METHOD

• POST https://www.kiran.com/addCourse

• {
• "courseName":“API Testing",
• "toolType":“Postman"
• }

• http method = POST


• protocol = https
• base URL = www.kiran.com
• end point = addcourse

• The payload/request body is


• {
• "courseName":“API Testing",
• "toolType":“Postman"
• }

• payload/request body ==> this is the data you are going to create on the server

During API TESTING, when the response code from the server received is :

2XX ➔ the test case has passed


4XX ➔ the test case has failed due to client side issues
46
5XX ➔ the test case has failed due to server side issues
API SYNTAX & API EXAMPLES WITH PUT METHOD
• PUT https://www.kiran.com/updateCourse?id=123

• {
• "courseName":“API Testing",
• "toolType":“Postman",
• "trainerName":"Kiran"
• }

• http method = PUT


• protocol = https
• base URL = www.kiran.com
• end point = updateCourse
• Query parameter:id=123

• The payload/request body is


• {
• "courseName":“API Testing",
• "toolType":“Postman",
• "trainerName":"Kiran"
• }

• payload/request body ==> this is the data you are going to update on the server
During API TESTING, when the response code from the server received is :

2XX ➔ the test case has passed


4XX ➔ the test case has failed due to client side issues 47
5XX ➔ the test case has failed due to server side issues
API SYNTAX & API EXAMPLES WITH DELETE METHOD

• DELETE https://www.kiran.com/deleteCourse?id=123

• http method = DELETE


• protocol = https
• base URL = www.kiran.com
• end point = deleteCourse
• Query parameter: id=123

During API TESTING, when the response code from the server received is :

2XX ➔ the test case has passed

4XX ➔ the test case has failed due to client side issues

5XX ➔ the test case has failed due to server side issues

48
WHAT IS API TESTING

49
WHAT IS API TESTING

• API testing is a type of software testing that involves testing application programming
interfaces (APIs) directly and as part of integration testing to determine if they meet
expectations for functionality, reliability, performance, and security

• Since APIs lack a GUI, API testing is performed at the business layer

• During the API testing, the data is exchanged from XML or JSON through HTTP requests
and responses

• These are technology independent and will work with a variety of the programming
languages and technologies

• APIs, or Application Programming Interfaces, are the connecting tissue between


different systems or layers of an application.

• Applications often have three layers: a data layer, a service (API) layer, and a
presentation (UI) layer. The API layer contains the business logic of an application - the
rules of how users can interact with services, data, or functions of the app.

• Because the API or service layer directly touches both the data layer and the
presentation layer, it presents the sweet spot of continuous testing for QA and
Development teams.

50
WHAT IS API TESTING

• API testing uses a software/HTTP client to send calls to the API and receive the
output/response

• API testing treats the component under test as black box

• The goal of API testing is to verify correct performance and error handling of the
component prior to its integration into an application

• Instead of using standard user inputs(keyboard) and outputs, in API Testing, you use
software to send calls to the API, get output, and note down the system's response

• API Testing requires an application to interact with API. In order to test an API, you will
need to

• Use Testing Tool to drive the API


• Write your own code to test the API

• API consists of a set of classes / functions / procedures which represent the business
logic layer. If API is not tested properly, it may cause problems not only the API
application but also in the calling application

51
WHAT IS API TESTING

52
WHAT IS API TESTING

53
API TESTS TO INCLUDE
What exactly needs to be verified in API Testing?

Basically, on API Testing, we send a request to the API with the known data and we analyse the response.

• Data accuracy
• HTTP status codes
• Response time
• Error codes in case API returns any errors
• Authorization checks
• Non functional testing such as performance testing, security testing

API FUNCTIONAL TESTING

API PERFORMANCE TESTING

API SECURITY TESTING

API THROTTLE TESTING

API DATA DRIVEN TESTING

API AUTOMATION TESTING

API HTTP HEADERS TESTING

OTHERS → STATUS CODE, STATUS DESCRIPTION, RESPONSE


SIZE, AUTHORIZATION CHECKS ETC 54
WHAT TO LOOK FOR IN API TESTING/TEST CASES

• Return value based on input condition: it is relatively easy to test, as input can be
defined and results can be authenticated

• Does not return anything: When there is no return value, behavior of API on the system
to be checked

• Trigger some other API/event/interrupt: If output of an API triggers some event or


interrupt, then those events and interrupt listeners should be tracked

• Update data structure: Updating data structure will have some outcome or effect on
the system, and that should be authenticated

• Modify certain resources: If API call modifies some resources then it should be validated
by accessing respective resources

55
TYPES OF API TESTING

56
TYPES OF API TESTING

• Functionality Testing → The API technically works

• Usability Testing → The API is easy to work with i.e., this testing verifies whether the API is
functional and user-friendly. And does API integrates well with another platform as well

• Reliability Testing → The API can be consistently connected to and lead to consistent results

• Load Testing → The API can handle a large amount of calls

• Security Testing → The API has defined security requirements such as what type of
authentication is required, permission and access controls and whether sensitive data is
encrypted over HTTP or both

• API Documentation/Discovery Testing → The API documentation easily guides the user to use
the APIs i.e., the test group should manually execute the set of calls documented in the API
like verifying that a specific resource exposed by the API can be listed, created and deleted
as appropriate

• Automated Testing → API testing should culminate in the creation of a set of scripts or a tool
that can be used to execute the API regularly

57
TYPES OF API TESTING
• POSITIVE TESTING ==>

1. RESPONSE CODE TESTING

2. RESPONSE BODY TESTING

3. RESPONSE TIME TESTING

4. COOKIES TESTING [test the API with cookies and without cookies]

5. RESPONSE BODY SIZE TESTING

6. RESPONSE HEADERS TESTING [how API behaves when the API request goes from different
browsers]

7. PERFORMANCE/LOAD TESTING [execute the APIs multiple times]

8. CONTINUOUS TESTING/API HEALTH CHECK TESTING [schedule the API tests to run on a
scheduled basis]

9. AUTOMATION TESTING [write java scripts to automate test cases]

10. COMMAND LINE TESTING/NON GUI TESTING

11. DATA DRIVEN TESTING [csv or json external test data]

12. THROTTLE TESTING/RATE LIMITING TESTING [subject the server to multiple API hits] 58
TYPES OF API TESTING

• NEGATIVE TESTING ==>

1. PROTOCOL TESTING [use HTTP instead of HTTPS ; use HTTPS instead of HTTP]

2. HTTP METHODS TESTING [use other HTTP methods against the API which is not proposed by the
Developer for the said API]

3. QUERY PARAMS TESTING [test with all query params as defined by Dev ; test with few query
params in the API ; tamper the query params and try the API ; increase the # of query
params and try the API ;

4. REQUEST BODY TESTING [test with empty payload ;test with empty values for the request
payload ; test with additional number of fields in the request payload; test with invalid key-
value pairs]

5. COOKIES TESTING [test if a Cookie is received when you use HTTP protocol ; test if the SECURE
flag is TRUE in Cookie properties]

6. THROTTLE TESTING/RATE LIMITING TESTING [test if the rate limit of accessing the APIs from a
given IP address is defined by the developer at the server side]

7. HEADERS TESTING [test if the request headers & response headers reveals any application or
server weaknesses and check if they are also revealing any fingerprint details]

59
API TESTING vs UNIT TESTING

UNIT TESTING API TESTING


Developers perform it Testers perform it

Separate functionality is tested End to end functionality is tested

Developer can access the source code Testers cannot access the source code

UI testing is also involved Only API functions are tested

Only basic functionalities are tested All functional issues are tested

Limited in scope Broader in scope


Usually ran before check-in Ran after build is created

60
ADVANTAGES OF API TESTING
• Time Effective/Earlier Testing: With API testing, once the logic is designed, tests can be built to
validate the correctness in responses and data. We don't have to wait for various teams to
finish their work or for full applications to be built - test cases are isolated and ready to built
immediately.

• Language independent

• Test core functionality

• Reduce testing costs/ Faster Time To Resolution: When API tests fail, we know exactly where
our system broke and where the defect can be found. This helps reduce time triaging bugs
between builds, integrations, and even different team-members. The small, isolated footprint
of an API test is perfect for faster MTTR stats, a valuable KPI for DevOps teams.

• Reduced risks/ Easier Test Maintenance: UIs are constantly changing and moving around
based on how they are accessed - browsers, devices, screen orientation, etc. This creates a
nightmare scenario where tests are being constantly rewritten to keep up with the actual
code in production. API changes are much more controlled and infrequent - often times API
definitions files like OpenAPI Spec can help make refactoring tests only a seconds of work.

• Ease of automation/Speed and Coverage of Testing: 300 UI tests may take 30 hours to run.
300 API tests could be run in 3 minutes. That means you’ll find more bugs in less time, while
also being about to fix them immediately.

61
BENEFITS OF API TESTING

•Early Testing –
With API testing, once the logic is designed, tests can be built to validate the correctness in
responses and data. We don’t have to wait for various teams to finish their work or for full
applications to be built – test cases are isolated and ready to built immediately.

•Easier Test Maintenance –


UIs are constantly changing and moving around based on how they are accessed – browsers,
devices, screen orientation, etc. This creates a nightmare scenario where tests are being
constantly rewritten to keep up with the actual code in production. API changes are much
more controlled and infrequent – often times API definitions files like OpenAPI Spec can help
make refactoring tests only a seconds of work.

•Faster Time To Resolution –


When API tests fail, we know exactly where our system broke and where the defect can be
found. This helps reduce time triaging bugs between builds, integrations, and even different
team-members. The small, isolated footprint of an API test is perfect for faster MTTR stats, a
valuable KPI for DevOps teams.

•Speed and Coverage of Testing –


100 UI tests may take 10 hours to run whereas 100 API tests could be run in 1 hour too. That
means we can find and fix more bugs in less time.

62
AN EXAMPLE OF API TESTING

63
AN EXAMPLE OF API TESTING
• The below example is a fairly simple and common functional test occurring at the UI level.
We're heading to a website, filling out a form, submitting the form, and verifying that we are
brought to the next screen.

64
AN EXAMPLE OF API TESTING
At the UI level, this simple test can present us with a couple of challenges. First, we are
hampered by the physical limits of our browser and network connection, having to load the
browser each time we want to run an iteration of this test. Second, any of these elements could
change on the screen and our test would fail - if the "Dogs" entry is covering the "Cat" entry, we
wouldn't be able to click it and our tests would fail. These challenges are annoying on their own
- now try driving 10,000 different names and combinations through this form and see your build
time grind to a halt.

With API Testing, this entire testing scenario can, and should, be boiled down to one step:

65
TYPES OF BUGS API TESTING DETECTS

• Fails to handle error conditions gracefully

• Unused flags

• Missing or duplicate functionality

• Reliability Issues. Difficulty in connecting and getting a response from API.

• Security Issues

• Multi-threading issues

• Performance Issues. API response time is very high.

• Improper errors/warning to caller

• Incorrect handling of valid argument values

• Response Data is not structured correctly (JSON or XML)

66
TYPES OF BUGS API TESTING DETECTS

67
CHALLENGES IN API TESTING

• Main challenges in Web API testing is Parameter Combination, Parameter


Selection, and Call Sequencing

• There is no GUI available to test the application which makes difficult to give
input values

• Validating and Verifying the output in a different system is little difficult for testers

• Parameters selection and categorization is required to be known to the testers

• Exception handling function needs to be tested

• Coding knowledge is necessary for testers

68
BEST PRACTICES OF API TESTING

• Test cases should be grouped by test category

• On top each test, you should include the declarations of the APIs being called.

• Parameters selection should be explicitly mentioned in the test case itself

• Prioritize API function calls so that it will be easy for testers to test

• Each test case should be as self-contained and independent from dependencies as


possible

• Avoid "test chaining" in your development

• Special care must be taken while handling one time call functions like - Delete, Close
Window, etc...

• Call sequencing should be performed and well planned

• To ensure complete test coverage, create test cases for all possible input combinations of
the API.

69
WHAT IS POSTMAN

70
WHAT IS POSTMAN
• The postman application is a HTTP client/request builder that enables easy interaction
with an API, without the need for a detailed knowledge of the coding required.

• Postman is a collaboration platform for API testing. Postman's features simplify each
step of testing an API and streamline collaboration so you can test the APIs—faster.

• Postman is

• Free/open-source
• Very popular
• HTTP client
• Ease to use
• Works with CI tools like Jenkins
• there is a big community around it which is growing
• New features are continuously being added, every 2 weeks

• Postman is available as a native app for Mac, Windows, and Linux operating systems.

71
WHAT IS POSTMAN

72
DOWNLOAD/INSTALL POSTMAN
NATIVE POSTMAN APP:

• To download Postman for free, visit https://www.postman.com/downloads/

Windows, Mac OS, Linux installation:

• Download the setup file


• Run the installer, from your DOWNLOADS folder

For using Postman on the browser,

• Use the web version https://www.postman.com


• Login to your postman account

73
DOWNLOAD/INSTALL POSTMAN
• Download Windows 64 bit version, if your PC is Windows 64 bit machine

• Download Windows 32 bit version, if your PC is Windows 32 bit machine

74
DOWNLOAD/INSTALL POSTMAN
Once it is downloaded, you can find your downloaded file in the default downloads
location of your system. If you are using Chrome browser, the downloaded file will appear
at the bottom of the browser as shown in the below image.

75
DOWNLOAD/INSTALL POSTMAN
Open Postman windows 64 bit exe file to install it on your system

Wait until the installation of Postman is completed on your PC

76
DOWNLOAD/INSTALL POSTMAN

Once installation of Postman is completed, you will be asked to create an account. You
can create an account later time by clicking on “Take me straight to the app, I’ll create
an account another time” link.

Note: I highly recommend you to create an account in the beginning itself. If you have
an account, it will allow you to save your work that you do inside postman. You wont
lose any of your work.
77
DOWNLOAD/INSTALL POSTMAN
For complete details on

• Downloading Postman on Windows, Mac, Linux


• Installation of Postman on Windows, Mac, Linux

visit

https://learning.postman.com/docs/getting-started/installation-and-updates/#installing-
postman-on-windows

78
LAUNCHING POSTMAN
To open Postman on your PC:

• As a program:

1. Treat it as you would any other program, for example by opening it via the
Start Menu on Windows OS

79
LAUNCHING POSTMAN
This will open a new window for the Postman app:

80
POSTMAN WORKSPACES

81
POSTMAN WORKSPACES
WORKSPACES:

An API project repository is called as a Workspace. Workspaces allow you to organize


your Postman work and collaborate with teammates. You can group your projects
together, with workspace acting as the single source of truth for related APIs, collections,
environments, mocks, monitors, and other linked entities. By collaborating in a workspace,
your edits are synced with your team in real time.

There are 4 types of Workspaces in Postman tool:

(i) Personal workspace ==> Personal workspaces are visible only to you—with a Postman
account you can create unlimited workspaces.; this is a FREE feature

(ii) Team workspace ==> along with you, the team members of your workspace can
view/edit the API test cases ; With team workspaces, you can share and manage access
to project components with collaborators ; this is a FREE feature

(iii) Public workspace ==> this workspace is available for read only for all Postman logged
in users (public) ; do not make your workspaces public if its your company/enterprise
project, as your API test cases will be publicly exposed ; this is a FREE feature

(iv) Private workspace ==> a private workspace is a team workspace that is only visible to
the user who created it, plus team members who have been invited to join it. Private
workspaces allow teams to restrict access to collections, environments, mocks, and
monitors that are relevant only to a particular group. this is a PAID feature that comes with
Business or Enterprise Postman plans 82
CREATING A WORKSPACE
To create a new workspace, select the workspace dropdown menu at the left of Postman,
and click New Workspace.

Use the visibility dropdown to choose


a Team, Private or Personal workspace.
Note that you can share elements to a
different workspace at a later date if you
are not sure which type to create.

There are four types of workspaces:

Personal, Team, Private and Public


workspaces

When you open a workspace, Postman


will provide an overview of its contents,
activity, and members in a new tab.
Open the workspace menu, then click +
New Workspace.

83
CREATING A WORKSPACE
To create a new workspace, you can click the New button above the navigation bar,
select Workspace and follow the same steps.

84
CREATING A WORKSPACE
You can also create a new workspace in the Workspaces dashboard. Click Create
New and follow the same steps.

85
CREATING A PERSONAL WORKSPACE

86
CREATING A PERSONAL WORKSPACE
To create a personal workspace, enter the workspace name and summary. Select the
visibility dropdown menu and choose Personal.

87
CREATING A TEAM WORKSPACE

88
CREATING A TEAM WORKSPACE
To create a team workspace, enter the workspace name and summary. Select the visibility
dropdown menu and choose Team.

Add collaborators by entering their email addresses, then define their workspace roles.

Click Create
Workspace and
Postman will open
your new workspace.
You can add
elements to the
workspace and invite
new members using
the Invite button at
the top at any time.

89
CREATING A PUBLIC WORKSPACE

90
CREATING A PUBLIC WORKSPACE
Public workspaces enable you to browse and collaborate on entities with anyone across
the world. Before you create a public workspace, navigate to team profile settings and
enable your public team profile. This will ensure your team's profile will show up on the Public
API Network.

91
CREATING A PUBLIC WORKSPACE
Once you make a workspace public, the notification is sent to workspace members. Click
the notification bell in the top right corner to view notifications.

92
CREATING A PUBLIC WORKSPACE
In addition to this, you will receive an email with the workspace information regarding who
has made the change and which workspace was affected with the sharing link for the
workspace.

93
ACCESSING WORKSPACES

94
ACCESSING WORKSPACES
You can access personal, team, and private workspaces using the workspace selector at
the top of Postman.

To view and edit your workspace details (e.g. name, description), navigate to the
workspace selector and hover over a workspace. Then, click ... and select View Details.

95
ACCESSING WORKSPACES
You can access public workspaces via the Workspaces category in the API Network.

96
MANAGING TEAM MEMBERS IN
WORKSPACES

97
MANAGING WORKSPACE MEMBERS
If you're a team administrator you can manage the members of your workspace, from the
Dashboard Overview via the Members tab.

For a team workspace, you can add or remove any team member or group from
the Members section, selecting access permissions depending on your account level, and
save your changes.

98
MANAGING WORKSPACE MEMBERS
Being an admin, you have the permission to add and remove any member from a public
workspace. To add members to a public workspace, navigate to the Members section,
enter an email address, click Add to the team, then Save.

Another way to add workspace members is to


click Manage Team and select Invite Users.

99
SEEING WHO IS IN YOUR WORKSPACE
You can see all of the members of your workspace and keep track of who's working on
your APIs at any given time. You can also make sure that all teammates who should be
included in your workspace are there. The avatars of workspace members at the top of the
screen in Postman are bright when a member is active, and muted when someone hasn't
been active for fifteen to twenty seconds.

Hover over the avatars to see your teammates names.

If more than three people belong to a workspace,


the fourth avatar will be a number representing
the remaining members. Click the number to see a
list of all active and inactive users.

100
DELETING WORKSPACES

101
DELETING WORKSPACES
When you delete a workspace, you erase its existence in Postman. Only the original creator
of a workspace or a team admin can delete a workspace.

"My Workspace" and "Team Workspace" are default workspaces created by Postman. They
cannot be deleted, however they can be renamed.

To delete a workspace, go to the Workspaces dashboard and select a workspace.


Click the ... on the right corner of the workspace overview, then select Delete workspace.

102
POSTMAN LANDSCAPE

103
API REQUEST & HTTP METHOD
• Request URL:

The Request URL is entered into the ‘Enter request URL here’ box

• Command:

To the left of the ‘Enter request URL here’ box there is a dropdown menu with
the options:

• ‘Get’,
• ‘Post’,
• ‘Put’,
• ‘Patch’,
• ‘Delete’,
• ‘Copy’,
• ‘Head’,
• ‘Options’,
• ‘Link’,
• ‘Unlink’,
• ‘Purge’,
• ‘Lock’,
• ‘Unlock’,
• ‘Propfind’
• ‘View’

104
QUERY PARAMETERS
Parameters:

To the right of the ‘Enter request URL here’ box there is a ‘Params’ button. This button reveals
a two rows below the ‘Enter request URL here’ box. The top row displays ‘Path variable key’
and ‘value’. The lower row displays ‘URL Parameter Key’ and ‘value’. To add another ‘URL
Parameter Key’ row begin to fill in the previous and one will appear below.

105
POSTMAN OPTIONS
• Options: Underneath the ‘Enter request URL here’ box or the ‘URL Parameter Key’ box, if
selected, there are five options.

• These are ‘Authorization’, ‘Headers (0)’, ‘Body’, ‘Pre-request script’, and ‘Tests’.

106
AUTHORIZATION
• Authorization:

Selecting reveals a
drop down menu,
located below the
Authorization button.
This drop down menu
has the options:

• ‘No Auth’,
• API Key
• Bearer Token
• ‘Basic Auth’,
• ‘Digest Auth’,
• ‘OAuth 1.0’,
• ‘OAuth 2.0’

The default selection is


‘Inherit auth from
parent’

107
POSTMAN & API
An API request lets you contact a server with API endpoints that you want to reach and
perform some action. Those actions are HTTP methods.

The most common methods are GET, POST, PUT, and DELETE. The names of the methods are
self-explanatory.

For example:

• GET enables you to retrieve data from a server


• POST enables you to add data to an existing file or resource in a server
• PUT lets you replace an existing file or resource in a server
• DELETE lets you delete data from a server

Postman makes sending API requests simple. Instead of testing your APIs through a command
line or terminal, Postman offer an intuitive graphical interface that is quick to learn and
rewarding to master.

108
POSTMAN – HOW IT WORKS
As you can see in the image below, when you enter a request in Postman and click the Send
button, the server receives your request and returns a response that Postman displays in the
interface.

109
REQUEST HEADERS
Headers (5):

Selecting Headers, reveals rows of details that has the Request Headers which will be sent
from client to server. The request headers follows a Key-Value pair.

110
REQUEST BODY
Body:

Body is only available as an option when using the commands: ‘Post’, ‘Put’, ‘Patch’,
‘Delete’.

Selecting reveals four options, these are:

• ‘form-data’,
• ‘x-www-form-urlencoded’,
• ‘raw’,
• ‘binary’

Form-data:

Selecting reveals a row below with ‘Key’ and ‘Value’ as headings, with a dropdown
menu of text or file.

X-www-form-urlencoded:

Selecting reveals a row below with ‘Key’ and ‘Value’ as headings.

111
REQUEST BODY
Raw:

Selecting reveals text box with numbered rows, and a drop down menu. The dropdown
menu includes:

• ‘Text’,
• ‘Text (text/plain)’,
• ‘JSON (application/json)’,
• ‘Javascript (application/javascript)’,
• ‘XML (application/xml)’,
• ‘XML (text/xml)’,
• ‘HTML (text/html)’

112
REQUEST BODY

113
PRE-REQUEST SCRIPTS

Pre-request script:

Postman allows users to do some JavaScript coding with which to manipulate the data
being sent with the request.

114
ENVIRONMENTS
Environments:

If you need to switch between different variables this is where environments come into
play. By switching environment and with no change in the request you can send different
parameters to API. Environments are managed from Settings icon in the top right corner
which opens a menu with “Manage Environments” link.

115
API TESTS
Tests:

The code snippets are used here to validate the API response against expected results
after the API is executed. The idea is that in many cases you will need to do something
with the response and extract a variable from it in order to use it at a later stage. This can
be done in “Tests” tab. You can put whatever JavaScript code you like in order to fulfill
your logic.

Send:

Use the send button in the top right corner of the window to send the API request to the 116
server
API TESTS
Tests:

After a response is received Postman has a functionality to make verifications on it. This is
done in “Tests” tab. Below is an example of different verifications. Below are few test
snippets offered by Postman tool:

pm.test("Status code is 200", function () {


pm.response.to.have.status(200);
});

pm.test("Content-Type is present", function () {


pm.response.to.have.header("Content-Type");
});

pm.test("Response time is less than 200ms", function ()


{
pm.expect(pm.response.responseTime).to.be.below(200
);
});

117
API TEST RESULTS

118
API RESPONSE
Returned messages:

After pressing send on a request the API sends a return message.

This is displayed below the Options, this message can include ‘Body’, ‘Cookies’ and
‘Headers’ and ‘Tests’

Body:

This can be displayed in ‘Pretty’, ‘Raw’, and ‘Preview’.

Within ‘Pretty’ are the options for ‘HTML’, ‘JSON’, ‘XML’, and ‘Text’

Cookies:

This shows the response cookies returned from the server

119
POSTMAN

120
HISTORY
History:

The Postman app has a ‘History’ section that records all of the requests. It is found on the
left of the screen. It saves the requests and allows them to be reopened even if the
application has been closed since. All requests you send using Postman are stored in the
history which you can access using the left sidebar. The history lets you experiment with
variations of requests quickly without wasting time in forming a request anew. You can
load a previous request by clicking on the request name.

121
POSTMAN VARIABLES
Variables

There are 2 types of variables – global and environment. Global variables are for all
requests, environment variables are defined per specific environment which can be
selected from a drop-down or no environment can be selected. Global variables are
editable by a small eye-shaped icon in the top right corner. Once defined variables can
be used in a request with format surrounded by curly brackets: {{VARIABLE_NAME}}.

122
POSTMAN COLLECTIONS
COLLECTIONS:

A Postman Collection lets you group


individual API requests together. You
can organize these requests into
folders.

Why Collections:

• You can group together requests


into folders and collections, so
that you don’t have to search
through your history repeatedly.

• You can add a name and


descriptions to requests, folders,
and collections. In Postman, you
can use the collection browser to
view the documentation.

• Postman Collections are a group


of saved requests you can
organize into folders.

123
POSTMAN COLLECTIONS
How to create collections:

You can create a new collection from the:

• Sidebar
• New button
• Launch screen

Sidebar:

In the sidebar, select “Collections” and click the “Collections” icon.

In the CREATE A NEW COLLECTION modal:

• Enter a name and optional description.


• Select an authorization type.
• Enter a pre-request script to execute before the collection runs.
• Add a test to execute after the collection runs.
• Add variables to the collection and its requests.

Click the Create button.

New button:

In the header toolbar, click the New button


124
POSTMAN COLLECTIONS
The Create New tab appears.

125
POSTMAN COLLECTIONS
In the Create New tab, click “Collection”.

In the CREATE A NEW COLLECTION modal:

• Enter a name and optional description.


• Select an authorization type.
• Enter a pre-request script to execute before the collection runs.
• Add a test to execute after the collection runs.
• Add variables to the collection and its requests.

Click the Create button.

After creating the collection, you can save requests to the collection and add folders for
better organization.

Note: At the bottom, you can select “Show this window at launch” to indicate whether
you want the Create New tab to display each time you open Postman.

Note: At the bottom, you can select “Show this window at launch” to indicate whether
you want the Create New tab to display each time you open Postman.

126
POSTMAN COLLECTIONS
Launch screen

The Create New tab appears by default when you launch Postman.
Open Postman.

In the Create New tab, click “Collection”.

In the CREATE A NEW COLLECTION modal:

• Enter a name and optional description.


• Select an authorization type.
• Enter a pre-request script to execute before the collection runs.
• Add a test to execute after the collection runs.
• Add variables to the collection and its requests.

Click the Create button.

After you save the request, you can add the URL, method, headers, and body to the
request in the builder.

127
POSTMAN COLLECTIONS
Saving a request to a collection

You can save a request to a collection from the:

• Request builder
• New button
• Launch screen

Build view

In the Workspaces build view, enter a new request in the builder.


Click the Save button.

In the SAVE REQUEST modal, enter a request name and select a collection or folder to
save the request.

Click the Save button.

128
POSTMAN COLLECTIONS
New button

In the header toolbar, click the New button.


Click “Request”.

In the SAVE REQUEST modal, enter a request name and select a collection or folder to
save the request.

Click the Save button.

After you save the request, you can add the URL, method, headers, and body to the
request in the builder.

Note: At the bottom, you can select “Show this window at launch” to indicate whether
you want the Create New tab to display each time you open Postman.

129
POSTMAN COLLECTIONS
Launch screen

The Create New tab appears by default when you launch Postman.

Open Postman.

• In the Create New tab, click “Request”.


• In the SAVE REQUEST modal, enter a title and description.
• Select a collection and save the request in an existing collection or create a new
collection.

Click the Save button.

Note: At the bottom, you can select “Show this window at launch” to indicate whether
you want the Create New tab to display each time you open Postman.

130
POSTMAN COLLECTIONS
Saving to a collection from history

Single request

To save a single request to a collection, hover over a request under the History tab and
click the plus (+) icon.

In the SAVE REQUEST modal, enter a title and description, select a collection, and save
the request in an existing collection or create a new collection.

Click the Save button.

Multiple requests

To save multiple requests, click the plus (+) icon that displays at the top of the sidebar.

In the SAVE MULTIPLE REQUESTS modal, select a collection or folders to save the requests.

Click the Save button.

131
POSTMAN COLLECTIONS
Duplicating an existing collection

In the sidebar, select “Collections”.


Click the ellipsis (…) to expand the control dropdown.

Select “Duplicate” from the menu.

Sharing collections

Postman enables you to share Collections in Workspaces from the Postman app and
the workspaces dashboard.

Note: Before you can upload or share a collection, you must sign in to your Postman
account. However, you can share collections as a file without being signed in.

132
COLLECTIONS
Sharing collections in the app

In the sidebar

In the Postman app, select a collection in the sidebar and click the ellipsis (…) button.
Select “Share Collection”.

The SHARE COLLECTION modal appears. It offers three ways to share a collection:

• Share in another workspace


• Embed
• Get Link

133
COLLECTIONS
Sharing collections in another workspace

Select this option to add a collection to another workspace. If added to a team


workspace, the collection will be visible to others on the team.

The collection’s creator can set team default permissions to either view only or edit. They
are also able to grant existing team members individual user permissions.

In the workspaces dashboard, select a collection and then click the Share button. The
collection is visible in your target workspace.

134
COLLECTIONS
Sharing collections with the Embed or Run In Postman button

Select this option to embed a Run in Postman button in your collection for your API
documentation, website, or Github readme.

The Run in Postman button lets anyone import and run this collection with one click.
When you click the Generate Code button, you get a link that you can use for a dynamic
or static button. You can also select the environment you want for the generated code.

The Run in Postman button shares the collection directly from Postman, so the collection is
uploaded to Postman servers when you generate the embed code.

135
COLLECTIONS
Sharing collections with a link

Select this option to generate a shareable link for others to access your collections. You
can manage a complete list of your collection links from your workspaces dashboard.

Sharing collections in the Dashboard

In the workspaces dashboard, select “Browse”, and then select a collection.


Click the Share button.

136
COLLECTIONS
Sharing as a file

You can download collections as a


JSON file to share with others, with or
without signing in to your Postman
account.

You can share collections


anonymously, but we strongly
recommend you sign in to your
Postman account when uploading
collections. When you’re signed in, you
can update your existing collection,
make it public, or delete it later.

137
COLLECTIONS
Create a new collection

Click the “new collection” icon on the top right, or save a current request to a new
collection.

138
COLLECTIONS
Favoriting a collection

If you’re working on a few collections in particular, you can click on the star icon to bring
the collection(s) to the top of the list.

Filter collections

If you have a lot of collections, filter collections in the sidebar using the search input field.

139
COLLECTIONS
Delete a collection

Click the ellipsis (…)next to a collection and select “Delete”. If


you didn’t intend to delete the collection, you can click
the Undo link in the notification that appears at the top of the
Postman app.

Click on Delete, to delete the collection from the Trash.

Recover a collection

Collections deleted within the past 24 hours can be recovered via


Trash. Locate the desired collection, hover your cursor over its row,
then click Restore.

Click on Delete, to delete the collection from the Trash.

140
ADDING FOLDERS
Adding folders

Folders are a way to organize your API


endpoints within a collection into intuitive
and logical groups to mirror your workflow.
Next to the collection to which you want
to add a folder, click on the ellipsis
(…) and select “Add Folder”.

Add a name and description to the


folder. Folders are initially ordered
alphabetically by name and folder name.
The description is reflected in your API
documentation.

You can add deeper levels of nesting for


folders. Drag and drop the folders to
reorder them to create the ultimate
customized folder structure.

141
POSTMAN SCRIPTS
Scripts in Postman

Postman contains a powerful runtime based on Node.js that allows you to add dynamic
behavior to requests and collections. This allows you to write test suites, build requests that
can contain dynamic parameters, pass data between requests, and a lot more. You can
add JavaScript code to execute during 2 events in the flow:

Before a request is sent to the server, as a pre-request script under the Pre-request
Script tab.

After a response is received, as a test script under the Tests tab.

Users can add pre-request and test scripts to a collection, a folder, a request within a
collection, or a request not saved to a collection.

Execution order of scripts


In Postman, the script execution order for a single request looks like this:
A pre-request script associated with a request will execute before the request is sent
A test script associated with a request will execute after the request is sent

142
POSTMAN SCRIPTS
• For every request in a collection, scripts will execute in the following order:
• A pre-request script associated with a collection will run prior to every request in the
collection.
• A pre-request script associated with a folder will run prior to every request in the folder.
• A test script associated with a collection will run after every request in the collection.
• A test script associated with a folder will run after after request in the folder.

143
POSTMAN SCRIPTS
For every request in a collection, the scripts will always run according to the following
hierarchy: collection-level script (if any), folder-level script (if any), request-level script (if
any).

Note that this order of execution applies to both pre-request and test scripts.

For example, imagine you had the following collection structured with a single folder and
2 requests within the folder.

144
POSTMAN SCRIPTS
Pre-request scripts

Pre-request scripts are snippets of code associated with a collection request that are
executed before the request is sent. This is perfect for use-cases like including the
timestamp in the request headers or sending a random alphanumeric string in the URL
parameters.

For example, to include a timestamp in the request headers, you can set an environment
variable with the value returned from a function.

145
POSTMAN SCRIPTS
You can then access the timestampHeader variable in the header data editor by
typing {{timestampHeader}}.

When the request is sent, your pre-request script will be executed, and the value of
timestampHeader will be sent in place of {{timestampHeader}}.

146
POSTMAN SCRIPTS
Adding a pre-request script to a collection or folder

Users can add pre-request scripts to a collection, a folder, or a single request within a
collection. A pre-request script associated with a collection will run prior to every request
in the collection. A pre-request script associated with a folder will run prior to every
request in the folder. This allows you to reuse commonly executed code prior to every
request.

Collection and folder scripts can be updated in the collection or folder details
respectively. Click on the ellipses (…) next to the collection or folder name, and select
“Edit” to open the modal.

Select the Pre-request Scripts tab to add and update the scripts. You can also add
collection scripts when initially creating the collection.

147
POSTMAN SCRIPTS
Test scripts

With Postman you can write and run tests for each request using the JavaScript language.
A Postman test is essentially JavaScript code executed after the request is sent, allowing
access to the pm.response object.

You can add as many tests as needed, depending on how many things you want to test
for. Tests are saved as part of collection requests.

This is perfect for both back-end and front-end developers to ensure that everything is
working properly with the API.

148
POSTMAN SCRIPTS
Snippets

While there are very few things to remember while writing tests, Postman tries to make the
process easier by listing commonly used snippets next to the editor. You can select the
snippet you want to add and the appropriate code will be added to the test editor. This is
a great way to quickly build test cases.

149
POSTMAN LANDSCAPE
Viewing results

Postman runs tests every time you run a request. Of course, you can choose to not look at
the test results!

Results are displayed in a Tests tab under the response viewer. The tab header shows how
many tests passed, and the test results are listed here. If the test evaluates to true, the test
passed.

150
POSTMAN EXECUTION ORDER OF SCRIPTS

In Postman, the script execution order for a single request looks like this:

•A pre-request script associated with a request will execute before the request is sent

•A test script associated with a request will execute after the request is sent

For every request in a collection, scripts will execute in the following order:

•A pre-request script associated with a collection will run prior to every request in the
collection.

•A pre-request script associated with a folder will run prior to every request in the folder.

•A test script associated with a collection will run after every request in the collection.

•A test script associated with a folder will run after request in the folder.
151
POSTMAN EXECUTION ORDER OF SCRIPTS

For every request in a collection, the scripts will always run according to the following
hierarchy:

collection-level script (if any), folder-level script (if any), request-level script (if any). Note
that this order of execution applies to both pre-request and test scripts.

152
POSTMAN VARIABLES
Intro to environments and globals

To understand environments and globals, you must first understand how variables work in
Postman.

Variables

Developers know that variables are symbolic names that represent the information you
store in them. The information the variable represents can change, but the operations on
the variable remain the same. Variables in Postman work the same way.
You can reuse the value of a variable in multiple places. If you change the value of a
variable, each instance of that variable changes to the new value.

Let’s say you have three API endpoints that use the same domain - your-domain.com.
You can save this domain as a variable and instead of repeating the value, you can
use /endpoint1 and /endpoint2 in the request builder. Now, if your domain changes
to another-domain.com, you only have to change this value once.

With Postman’s scripting engine you can set variable values, copy data from one request,
and use it in another request.

In a nutshell, variables enable you to:

• Reuse values to keep your code DRY (Don’t Repeat Yourself).


• Configure your setup to accommodate the environment of differnet users.
• Extract data from responses and chain requests in a collection. 153
POSTMAN VARIABLES
Environments

An environment is a set of key-value pairs. The key represents the name of the variable.
You can use a data editor to modify an environment.

While working with APIs, you often need different setups for your local machine, the
development server, or the production API. Environments let you customize requests using
variables so you can easily switch between different setups without changing your
requests.

You won’t have to remember all those values once they are in Postman. You can
download environments, save them as JSON files, and upload them later.

You can create, share, duplicate, export, and delete an environment. You can also
import an environment as a single JSON file.

Note: Environment and global variables are always stored as strings. If you’re storing
objects or arrays, be sure to JSON.stringify() them before storing, and JSON.parse() them
while retrieving.

154
POSTMAN VARIABLES
Globals

Global variables provide a set of variables that are always available to you in all scopes.
You can have multiple environments, but only one can be active at a time with one set of
global variables, which are always available.

Note: Environment and global variables are always be stored as strings. If you’re storing
objects or arrays, be sure to JSON.stringify() them before storing, and JSON.parse() them
while retrieving.

155
POSTMAN VARIABLES
Variable scopes

You can assign five types of variable scopes:

• Global
• Collection
• Environment
• Local
• Data

You can view different kinds of buckets in which values reside. If a variable is in two
different scopes, the scope with a higher priority wins and the variable gets its value from
there. Postman resolves scopes using this hierarchy progressing from broad to narrow
scope.

If a variable from the currently active environment shares its name with a global variable,
the environment variable will take priority. In other words, global variables are overridden
by environment variables, which are overridden by data variables (only available in
the collection runner).

You can use variables in the following form in the Postman user interface -
`{{variableName}}`.

The string `{{variableName}}` will be replaced with its corresponding value when Postman
resolves the variable. 156
POSTMAN – IMPORT FEATURE
Working with data files

Using data files is a powerful way to test the behavior of APIs with varying data in
unexpected circumstances. We can think of data files as parameters for each iteration of
a collection run.

Importing sample files


To import the files in Postman, click the Import button in the header bar. In
the IMPORT modal, select the sample files to upload.

157
POSTMAN MONITORS
POSTMAN MONITORING

Postman monitoring lets you run a collection periodically to check for its performance
and response. You can set up a monitor to run as frequently as 5 minutes to check if all
the requests in your collection are up and healthy.

When you set up a monitor, Postman servers will hit the endpoints in your collection
according to the specified frequency. You can also select a
corresponding environment to use and store variables.

If you have written tests for your requests , the monitor would run these tests to validate
the response and notify you when a test fails. You can configure how to receive the alerts
from a wide number of integrations available.

Setting up a monitor

Postman lets you monitor shared or private collections. If you choose to monitor a shared
collection, your team can see the monitor. If you create a monitor on an unshared
collection, the monitor is private and only visible to you.

You can create a monitor from the:

• Sidebar
• New button
• Launch screen
• Postman web 158
POSTMAN MONITORS
Sidebar

You can create a monitor for an existing collection from the sidebar.

In the Postman app, click on the ellipses (…) next to the collection
you want to monitor.

Select "Monitor Collection".

In the MONITOR COLLECTION modal, you must:

• Enter the name of the monitor.


• Select an environment (optional).
• Set how frequently the monitor should run. For more information
on how to schedule a monitor, see the “Monitoring schedule and
region” section below.
• Select one or more regions of the world from where you want to
monitor your results.

You can also select advanced monitor options to receive email


notifications for run failures and errors, request a timeout, request a
delay, not follow redirects, and disable SSL validation.

159
POSTMAN MONITORS

Click the Monitor this collection button.

160
POSTMAN – SIMPLE COMMANDS

Console.log(“Hello world”)
console.log(request.data)
console.log(request.url)
console.log(request.method)

console.log(responseBody)
console.log(responseCode)

Console.log(typeof responseHeaders)
Console.log(typeof responseTime)
Console.log(typeof responseBody)
Console.log(typeof responseCode)

json1= JSON.parse(responseBody)
console.log(json1.id)
console.log(json1.title)

console.log(responseTime)
console.log(responseCode.code)
console.log(responseCode.name)
console.log(responseCode.detail)

161
POSTMAN – SIMPLE COMMANDS

console.info("This is info");

console.log("This is log");

console.error("This is error");

console.warn("This is warning");

162
POSTMAN – SIMPLE COMMANDS

for(i=1;i<=10;i++)
{
console.log(i)
}

i=1
while(i<=10)
{
console.log(i)
i++
}

input=11
for(i=1;i<=10;i++)
{
console.log(input*i)
}

163
WHAT IS NEWMAN
Newman is Postman’s open-source tool to run and test collections directly from the
command line. Powered by the same runtime that powers the Postman native apps, see
how the Newman CLI can streamline your API testing.

The Newman CLI can help you run and test your collection ONCE or EVERY time you
make changes.

Newman supports a variety of output formats, including a human-friendly console output,


as well as outputting to a JSON or HTML file.

Run from command line:

In order to run Postman tests in the command line as part of some CI process, there is a
separate tool called Newman. It requires NodeJS to be installed and runs on NodeJS
environment.

Newman is a command line Collection Runner for Postman. It allows you to run and test a
Postman Collection directly from the command line. It is built with extensibility in mind so
that you can easily integrate it with your continuous integration servers and build systems.

Newman maintains feature parity with Postman and allows you to run collections the way
they are executed inside the collection runner in the Postman app.

164
WHAT IS NEWMAN
• Newman is

• Free/open-source
• Very popular
• Works seamlessly with Postman
• Ease to use
• Executes tests from the command line so that they can be included in CI

Newman is built on Node.js. To run Newman, make sure you have Node.js installed.

After you install Node.js, Newman is just a command away.

Install Newman from npm globally on your system, which allows you to run it from
anywhere.

$ npm install -g newman

165
WHAT IS NEWMAN

NEWMAN is
• CLI TOOL DEVELOPED FOR POSTMAN
• USED TO GENERATE CLI REPORTS (CLI=Command Line Interface)
• USED TO GENERATE JSON REPORTS
• USED TO GENERATE HTML REPORTS
• FOR BETTER VISUALIZATION OF API TEST REPORTS
• FOR EASE OF DEBUGGING & TROUBLESHOOTING API TESTS
• FOR EFFECTIVE COVERAGE OF TESTING

TO INSTALL NEWMAN, PRE-REQUISITES ARE


• NODE JS
• NPM
• NEWMAN REPORTING PACKAGES

All HTML reports will be created in NEWMAN folder, where collection.JSON files are stored
locally on your computer

166
NEWMAN COMMANDS
INSTALL NODE JS FROM https://nodejs.org/en/download/current/
• THIS WILL INSTALL NODE JS AND NPM PACKAGES AUTOMATICALLY
• Execute below commands to know if NodeJS is installed
node -v
• Execute below commands to know if NPM is installed
npm -v

INSTALL NEWMAN USING


npm install –g newman (g is for global installation on the local machine)

TO KNOW THE VERSION OF NEWMAN INSTALLED, RUN THE BELOW CMD:


newman run –v

TO GET HELP COMMANDS OF NEWMAN, RUN THE BELOW CMD:


newman run -h

167
NEWMAN COMMANDS
TO INSTALL HTML REPORTS USING NEWMAN, execute below command for html installation
npm install -g newman-reporter-html

WE CAN RUN NEWMAN COMMAND TO GENERATE HTML REPORT


newman run collection.json -r html
OR
newman run collectionURL -r html

WE CAN RUN NEWMAN COMMAND TO GENERATE CLI REPORT


newman run collection.json
OR
newman run collection URL

To run a collection with multiple # of iterations (load testing),


newman run collection.json -n no.of iterations (for CLI report)
newman run collection.json -n no.of iterations –r html (for HTML report)

168
NEWMAN COMMANDS
To run a collection and environment,
newman run collection name -e environment name

To run a collection with data file (.CSV or .JSON),

The below commands are without environment parameter:


newman run collection name -d fileName -n no.of iterations (for CLI report)
newman run collection name –d fileName -n no.of iterations –r html (for HTML
report)

The below commands are with environment parameter:


newman run collection name -d fileName -n no.of iterations -e environment name
(for CLI report)
newman run collection name -d fileName -n no.of iterations -e environment name –
r html (for HTML report)

To run a collection with delay time,


newman run collection name -d delaytime
newman run collection name -d delaytime -n no.of iterations (for CLI report)
newman run collection name -d delaytime -n no.of iterations –r html (for HTML
report)

169
NEWMAN COMMANDS
WE CAN RUN NEWMAN COMMAND TO GENERATE CUSTOM PROJECT TITLE IN THE REPORT

newman run collectionName -r htmlextra --reporter-htmlextra-title "My new report


title"

Show only Failures in HTMLExtra Report


newman run collectionName -r htmlextra --reporter-htmlextra-showOnlyFails

To know more about HTMLExtra Reporting features,


https://www.npmjs.com/package/newman-reporter-htmlextra

170
NEWMAN COMMANDS
The easiest way to run Newman is to run it with a collection. You can run any collection
file from your file system.

$ newman run mycollection.json

$ newman run collection_link

Newman provides a rich set of options to customize a run. You can retrieve a list of
options by running it with the -h flag.

171
NEWMAN COMMANDS
Use the -n option to set the number of iterations to run the collection.

$ newman run mycollection.json -n 10 # runs the collection 10 times

You can use the --bail flag to tell Newman to halt on a test case error with a status code
of 1, which can then be picked up by a CI tool or build system.

$ newman run PostmanCollection.json -e environment.json --bail newman

172
THANK YOU

173

You might also like