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

Lecture 20

API Testing is a software testing type that validates APIs by checking their functionality, reliability, performance, and security, focusing on the business logic layer rather than the GUI. It involves setting up a testing environment, writing test cases based on various output types, and using tools like Postman for execution. Key challenges include the lack of a GUI, parameter selection, and the need for coding knowledge, while best practices emphasize independent test cases and thorough documentation.

Uploaded by

belo4kaaly
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)
6 views

Lecture 20

API Testing is a software testing type that validates APIs by checking their functionality, reliability, performance, and security, focusing on the business logic layer rather than the GUI. It involves setting up a testing environment, writing test cases based on various output types, and using tools like Postman for execution. Key challenges include the lack of a GUI, parameter selection, and the need for coding knowledge, while best practices emphasize independent test cases and thorough documentation.

Uploaded by

belo4kaaly
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/ 39

API testing

What is an API?

API (Full form Application Programming Interface) enables communication and data exchange
between two separate software systems. A software system implementing an API contains
functions/sub-routines which can be executed by another software system.

What is API Testing?

API TESTING is a software testing type that validates Application Programming Interfaces
(APIs). The purpose of API Testing is to check the functionality, reliability, performance, and
security of the programming interfaces. In API Testing, instead of using standard user
inputs(keyboard) and outputs, you use software to send calls to the API, get output, and note
down the system's response. API tests are very different from GUI Tests and won't concentrate
on the look and feel of an application. It mainly concentrates on the business logic layer of the
software architecture.

https://www.youtube.com/watch?v=IUqzMWIuXG0

WATCH AT HOME

https://www.youtube.com/watch?v=QYg5z6EGOk4

API Testing requires an application that can be interacted via an 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

Set-up of API Test environment

●​ API Testing is different than other software testing types as GUI is not available, and yet
you are required to setup initial environment that invokes API with a required set of
parameters and then finally examines the test result.
●​ Hence, Setting up a testing environment for API testing seems a little complex.
●​ Database and server should be configured as per the application requirements.
●​ Once the installation is done, the API Function should be called to check whether that
API is working.

Types of Output of an API

An output of API could be

●​ Any type of data


●​ Status (say Pass or Fail)
●​ Call another API function.

Any Type of Data

Example: There is an API function which should add two integer numbers.

Long add(int a, int b)

The numbers have to be given as input parameters. The output should be a summation of two
integer numbers. This output needs to be verified with an expected outcome.

Calling needs to be done such as

add (1234, 5656)

Exceptions have to be handled if the number is exceeding the integer limit.

Status (say Pass or Fail)

Consider the below API function -

1.​ Lock()
2.​ Unlock()
3.​ Delete()

They return any value such as True (in case of success) or false (In case of error) as an output.

A more accurate Test Case would be, can call the functions in any of the scripts and later check
for changes either in the database or the Application GUI.

Calling of another API / Event

In this case, we call one of the API function which in turn will call another function.

For example - First API function can be used for deleting a specified record in the table and this
function, in turn, calls another function to REFRESH the database.

Test Cases for API Testing:

Test cases of API testing are based on

●​ 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, a behavior of API on the
system to be checked
●​ Trigger some other API/event/interrupt: If an 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

Approach of API Testing:

Following points helps the user to do API Testing approach:


1.​ Understanding the functionality of the API program and clearly define the scope of the
program
2.​ Apply testing techniques such as equivalence classes, boundary value analysis, and error
guessing and write test cases for the API
3.​ Input Parameters for the API need to be planned and defined appropriately
4.​ Execute the test cases and compare expected and actual results.

How to do API Testing


API testing should cover at least following testing methods apart from usual SDLC process

●​ Discovery testing: 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
●​ Usability testing: This testing verifies whether the API is functional and user-friendly.
And does API integrates well with another platform as well
●​ Security testing: This testing includes what type of authentication is required and
whether sensitive data is encrypted over HTTP or both
●​ 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
●​ Documentation: The test team has to make sure that the documentation is adequate and
provides enough information to interact with the API. Documentation should be a part of
the final deliverable

Best Practices of API Testing:

●​ Test cases should be grouped by test category


●​ On top of 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,
CloseWindow, 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.

Types of Bugs that 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 a caller
●​ Incorrect handling of valid argument values
●​ Response Data is not structured correctly (JSON or XML)
Tools for API testing

Since API and Unit Testing both target source code, tools/frameworks can be used for their
automation.

●​ Parasoft SOAtest
●​ Runscope
●​ Postman
●​ Curl
●​ Cfix
●​ Check
●​ CTESK
●​ dotTEST
●​ Eclipse SDK tool- Automated API testing

Check out top API Testing Tools List

Challenges of API Testing

Challenges of API testing includes:

●​ 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
What is a REST API?
An API or Application Programming Interface is a set of programming instructions for accessing
a web-based software application.

In other words, a set of commands used by an individual program to communicate with one
another directly and use each other's functions to get information.

Rest stands for Representational State Transfer. It is an architectural style and an approach for
communication used in the development of Web Services. REST has become a logical choice for
building APIs. It enables users to connect and interact with cloud services efficiently.

For example, a Google website can have API for various functions like search, translations,
calendars, etc.

In general API's are like below, they have server name, paths.., etc

http://<server name>/v1/export/Publisher/Standard_Publisher_Report?format=csv

There are mainly 4 methods involve in API Testing like GET, POST, Delete, and PUT.

●​ GET- The GET method is used to extract information from the given server using a
given URI. While using GET request, it should only extract data and should have no
other effect on the data.
●​ POST- A POST request is used to create a new entity. It can also be used to send data to
the server, for example, customer information, file upload, etc. using HTML forms.
●​ PUT- Create a new entity or update an existing one.
●​ DELETE - Removes all current representations of the target resource given by a URI.

How to Test REST API

API testing requires an application to interact with API. To test an API, you require two things,

●​ Testing Tool/Framework to drive the API


●​ Writing down your own code to test the API

Rest API can be tested with tools like:

●​ Advanced Rest Client


●​ Postman-Rest Client
●​ Curl in Linux

Steps for Testing REST API

http://ip.jsontest.com/

Step 1): Launch the app

Step 2): Enter the URL of the API in the URL textbox.

Step 3): Select the method for the type of HTTP method to hit- e.g. POST

Step 4): Provide Headers Set, in the Headers textbox. Click on Insert header set.

Step 5)

1.​ Now switch to Body Tab.


2.​ Set the required Body content type and Editor view e.g. Body content type :
application/json
3.​ Editor view : Raw input.
4.​ Under Payload, pass the request body of the API in the form of key-value pairs e.g.
{{"key1":"value1","key2":"value2"}. If it is post API, then we need to pass body or
parameters. We will pass under given payload.
{"property" : ["Sites"], "report_type" : ["ALL"]}

Step 6)

1.​ Hit the send button.


2.​ You can click on DETAILS button to see the Response headers.

Step 7)

1.​ Hit the send button.


2.​ You can click on DETAILS button to see the Response headers.
Here are the response details:

Validating the results

Mainly, for Web API Testing, we need to check response code, a response message, and response
body.

Below are the various response code, one might encounter while API Testing.
What is Postman?
Postman is currently one of the most popular tools used in API testing. It started in 2012 as a side
project by Abhinav Asthana to simplify API workflow in testing and development. API stands
for Application Programming Interface which allows software applications to communicate with
each other via API calls.

Why Use Postman?


With over 4 million users nowadays, Postman has become a tool of choice for the following
reasons:

1.​ Accessibility - To use Postman, one would just need to log-in to their own accounts
making it easy to access files anytime, anywhere as long as a Postman application is
installed on the computer.
2.​ Use of Collections - Postman lets users create collections for their API calls. Each
collection can create subfolders and multiple requests. This helps in organizing your test
suites.
3.​ Collaboration - Collections and environments can be imported or exported making it easy
to share files. A direct link can also be used to share collections.
4.​ Creating Environments - Having multiple environments aids in less repetition of tests as
one can use the same collection but for a different environment. This is where
parameterization will take place which we will discuss in further lessons.
5.​ Creation of Tests - Test checkpoints such as verifying for successful HTTP response
status can be added to each API calls which help ensure test coverage.
6.​ Automation Testing - Through the use of the Collection Runner or Newman, tests can be
run in multiple iterations saving time for repetitive tests.
7.​ Debugging - Postman console helps to check what data has been retrieved making it easy
to debug tests.
8.​ Continuous Integration - With its ability to support continuous integration, development
practices are maintained.

How to Download and Install POSTMAN

Being an Open Source tool, Postman can be easily downloaded. Here are the steps to install:

Step 1) Go to https://www.getpostman.com/downloads/ and choose your desired platform among


Mac, Windows or Linux. Click Download.
Step 2) Your download is in progress message should now display on the Apps page. Once the
download has completed, click on Run.

Step 3) Installation Starts


Step 4) In the next window, Signup for a Postman Account

NOTE: There are two ways to sign up for a Postman account. One is to create an own Postman
account, and the other is to use a Google account. Though Postman allows users to use the tool
without logging in, signing up ensures that your collection is saved and can be accessed for later
use.

Step 5) Select the workspace tools you need and click Save My Preferences
Step 6) You will see the Startup Screen
How to use Postman

Below is the Postman Workspace. Let's explore the different features of the tool!

1.​ New - This is where you will create a new request, collection or environment.
2.​ Import - This is used to import a collection or environment. There are options such as
import from file, folder, link or paste raw text.
3.​ Runner - Automation tests can be executed through the Collection Runner. This will be
discussed further in the next lesson.
4.​ Open New - Open a new tab, Postman Window or Runner Window by clicking this
button.
5.​ My Workspace - You can create a new workspace individually or as a team.
6.​ Invite - Collaborate on a workspace by inviting team members.
7.​ History - Past requests that you have sent will be displayed in History. This makes it easy
to track actions that you have done.
8.​ Collections - Organize your test suite by creating collections. Each collection may have
subfolders and multiple requests. A request or folder can also be duplicated as well.
9.​ Request tab - This displays the title of the request you are working on. By default,
"Untitled Request" would be displayed for requests without titles.
10.​HTTP Request - Clicking this would display a dropdown list of different requests such as
GET, POST, COPY, DELETE, etc. In testing, the most commonly used requests are GET
and POST.
11.​Request URL - Also known as an endpoint, this is where you will identify the link to
where the API will communicate with.
12.​Save - If there are changes to a request, clicking save is a must so that new changes will
not be lost or overwritten.
13.​Params - This is where you will write parameters needed for a request such as key values.
14.​Authorization - In order to access APIs, proper authorization is needed. It may be in the
form of a username and password, bearer token, etc.
15.​Headers - You can set headers such as content type JSON depending on the needs of the
organization.
16.​Body - This is where one can customize details in a request commonly used in POST
request.
17.​Pre-request Script - These are scripts that will be executed before the request. Usually,
pre-request scripts for the setting environment are used to ensure that tests will be run in
the correct environment.
18.​Tests - These are scripts executed during the request. It is important to have tests as it sets
up checkpoints to verify if response status is ok, retrieved data is as expected and other
tests.

Working with GET Requests

Get requests are used to retrieve information from the given URL. There will be no changes done
to the endpoint.

We will use the following URL for all examples in this tutorial

https://jsonplaceholder.typicode.com/users​

In the workspace

1.​ Set your HTTP request to GET.


2.​ In the request URL field, input link
3.​ Click Send
4.​ You will see 200 OK Message
5.​ There should be 10 user results in the body which indicates that your test has
run successfully.

*Note: There may be cases that Get request may be unsuccessful. It can be due to an invalid
request URL or authentication is needed.

Working with POST Requests

Post requests are different from Get request as there is data manipulation with the user adding
data to the endpoint. Using the same data from the previous tutorial in Get request, let's now add
our own user.

Step 1) Click a new tab to create a new request.


Step 2) In the new tab

1.​ Set your HTTP request to POST.


2.​ Input the same link in request url: https://jsonplaceholder.typicode.com/users
3.​ Switch to the Body tab

Step 3) In Body,

1.​ Click raw


2.​ Select JSON
Step 4) Copy and paste just one user result from the previous get request like below. Ensure that
the code has been copied correctly with paired curly braces and brackets. Change id to 11 and
name to any desired name. You can also change other details like the address.

"id": 11,

"name": "Krishna Rungta",

"username": "Bret",

"email": "[email protected]

​ ",

"address": {

"street": "Kulas Light",

"suite": "Apt. 556",

"city": "Gwenborough",

"zipcode": "92998-3874",

"geo": {

"lat": "-37.3159",
"lng": "81.1496"

},

"phone": "1-770-736-8031 x56442",

"website": "hildegard.org",

"company": {

"name": "Romaguera-Crona",

"catchPhrase": "Multi-layered client-server


neural-net",

"bs": "harness real-time e-markets"

]
*Note: Post request should have the correct format to ensure that requested data will be created.
It is a good practice to use Get first to check the JSON format of the request. You can use tools
like https://jsonformatter.curiousconcept.com/
Step 5) Next,

1.​ Click Send.


2.​ Status: 201 Created should be displayed
3.​ Posted data are showing up in the body.

How to Parameterize Requests


Data Parameterization is one of the most useful features of Postman. Instead of creating the same
requests with different data, you can use variables with parameters. These data can be from a
data file or an environment variable. Parameterization helps to avoid repetition of the same tests
and iterations can be used for automation testing.

Parameters are created through the use of double curly brackets: {{sample}}. Let's take a look at
an example of using parameters in our previous request:

Now let's create a parameterize get request.

Step 1)

1.​ Set your HTTP request to GET


2.​ Input this link: https://jsonplaceholder.typicode.com/users. Replace the first part of the
link with a parameter such as {{url}}. Request url should now be {{url}}/users.
3.​ Click send.
There should be no response since we have not set the source of our parameter.

Step 2) To use the parameter you need to set the environment

1.​ Click the eye icon


2.​ Click edit to set the variable to a global environment that can be used in all collections.

Step 3) In variable,

1.​ Set the name to the url which is https://jsonplaceholder.typicode.com


2.​ Click Save.
Step 4) Click close if you see the next screen
Step 5) Go back to your Get request then click send. There should now be results for your
request.
*Note: Always ensure that your parameters have a source such as an environment variable or
data file to avoid errors.

How to Create Postman Tests

Postman Tests are JavaScript codes added to requests that help you verify results such as
successful or failed status, comparison of expected results, etc. It usually starts with pm.test. It
can be compared to asserts, verify commands available in other tools.

Let's create some basic tests for our parameterize requests from the previous lesson.

Step 1) Go to your GET user request from the previous tutorial.

1.​ Switch to the tests tab. On the right side are snippet codes.
2.​ From the snippets section, click on "Status code: Code is 200".

The pane is auto-populated


Step 2) Now click Send. The test result should now be displayed.

Step 3) Go back to the test tab and let's add another test. This time we will compare the expected
result to the actual result.

From the snippets section, click on "Response body:JSON value check". We will be checking if
Leanne Graham has the userid 1.
Step 4)

1.​ Replace "Your Test Name" from the code with "Check if user with id1 is Leanne
Graham" so that the test name specifies exactly what we want to test.
2.​ Replace jsonData.value with jsonData[0].name. To get the path, check the body in Get
result earlier. Since Leanne Graham is userid 1, jsonData is in the first result which
should start with 0. If you want to get the second result, use jsonData[1] and so on for
succeeding results.
3.​ In to eql, input "Leanne Graham"

pm.test("Check if user with id1 is Leanne Graham", function () {

var jsonData = pm.response.json();

pm.expect(jsonData[0].name).to.eql("Leanne Graham");

});
Step 5) Click send. There should now be two passed test results for your request.

How to Create Collections

Collections play an important role in organizing test suites. It can be imported and exported
making it easy to share collections amongst the team. In this tutorial, we will learn how to create
and execute a collection.

Let's start in creating a collection:

Step 1) Click on the New button at the top left corner of the page.

Step 2) Select Collection. Create collection window should pop up.


Step 3) Input the desired collection name and description then click create. A collection should
now be created.
Step 4) Go back to the previous Get request. Click Save

Step 5)

1.​ Select Postman Test Collection.


2.​ Click Save to Postman Test Collection
Step 6) Postman test collection should now contain one request.
Step 7) Repeat steps 4-5 for the previous Post request so that collection will now have two
requests.
How to Run Collections using Collection Runner

There are two ways to run a collection which is the Collection Runner and Newman. Let's begin
by executing the collection in Collection Runner.

Step 1) Click on the Runner button found at the top of the page next to the Import button.

Step 2) Collection Runner page should appear such as below. Following is the description of
various fields
Step 3) Run your Postman Test Collection by setting up the following:

●​ Choose Postman test collection- Set iterations as 3


●​ Set delay as 2500 ms
●​ Click on Run Postman Test... button
Step 4) Run Results page should be displayed after clicking the Run button. Depending on the
delay, you should see the tests as they execute.

1.​ Once tests have finished, you can see the test status if it is Passed or Failed and the results
per iteration.
2.​ You see Pass status for the Get Requests
3.​ Since we did not have any tests for Post, there should be a message that the request did
not have any tests.

You can see how important it is that there are tests in your requests so that you can verify
HTTP request status if successful and the data is created or retrieved.

You might also like