API Testing
Types of API
API
Google FaceBook
REST API Methods / http request
1. get
2. post
3. put
4. delete
[Link]
[Link]
[Link]
Day 3
Postman – API Testing tool
We can do manual testing of API’s using Postman.
We have both Desktop/web versions.
Installation
Workspace : Area where we maintain files and save
Workspace operations: create/rename/delete
Collection: contains number of folders and HTTP requests
Collection operations: create/rename/delete and run the collection
We can create any number of collections under workspace
Request ---- API ---- Response
https requests
GET—retrieve the resource from database
POST-- create resource on database
PUT—update existing resource on database
PATCH—update partial resource details on database
DELETE—delete existing resource from database
Sample API:
URI
[Link]
Validations
1. Status code
2. Time
3. Size data
4. Response body (json/xml)
5. Cookies
6. Headers
http status codes
3 levels
200
400
500
Day 4
Step1)
NodeJS
Npm-node package manager
Step2)
j-son server
Creation of Dummy API’s
1) Install NodeJS
Download link: [Link]
Environment Variable
2) Check node and npm versions (npm comes along with [Link])
node –version
npm --version
3) Install json server
npm install –g json-server
4) json-server [Link]
tests/validations
JSON – Java Script Object Notation
Client--------JSON---------- Server
JSON
Key and Value pairs
Key is always included in “ “quotations
{
“name”:”John”,
“age”:30
}
Array
{
“firstname”:”John”,
“secondname”:null
“age”:30,
“phone”:[123456,458976]
“status”:true
}
Students data
Student—sid, sname and grad
{
“students”: stud1, stud2 and stud3… so array comes in picture
………..
{
"students":[
{"sid":101,
"sname":"John",
"grad":"A",
},
"sid":101,
"sname":"John",
"grad":"A",
},
{
"sid":102,
"sname":"Kim",
"grad":"B",
},
{
"sid":103,
"sname":"Scott",
“grad”:”C”
}
]
}
JSON Object and JSON Array
JSON ARRAYS
key values pairs
key: value
key is always included in " " quotation
"firstname": "John",
"secondname": null
"age": 30,
"phone": [12345,678976 ]
"status": true
}
students data
-------------
student -- sid, sname , grad
"students": [100,200,300]
"students": ["A","B","C"]
------------------------------------------------
"students":[
"sid" : 101,
"sname" : "John",
"grad": "A"
},
"sid": 102,
"sname": "Kim",
"grad": "B"
},
"sid": 103,
"sname": "Scott",
"grad": "C"
students[0].name ------> John
students[2].sid -------> 103
Day 6
Response Validations
Status Code
Headers
Cookies
Response time
Response Body
Assertion-validation
pm-library
functions
javascript
function
Arrow function
Chai Assertion Library
[Link] (“Test Name”, function()
//assertion;
);
[Link] (“Test Name”, () =>
//assertion;
);
Testing Status Codes
Test for the response status code:
[Link]("Status code is 200", function () {
[Link](200);
});
If you want to test for the status code being one of a
set, include them all in an array and use of
[Link]("Successful get request", function () {
[Link]([Link]).[Link]([200, 201])
;
});
Check the status code text:
[Link]("Status code has string", function () {
[Link]("Created");
});
[Link]("Response status code is 201", function () {
[Link](201);
});
Testing Headers
Check that response header is present;
[Link]("Content-Type header is present", function () {
[Link]("Content-Type");
});
Test for response header having a particular value;
[Link]("Content-Type header is application/json", func
tion () {
[Link]([Link]("Content-Type"))
.[Link]('application/json; charset=utf-8');
});
Testing Cookies
Check that response header is present;
[Link]("Content 'language' is present", function () {
[Link]("Cookies");
});
Test for response header having a particular value;
[Link]("Cookie 'language' has value 'en-gb'", function
() {
[Link]([Link]("Cookies")).[Link]
l("en-gb");
});
Testing Response Data
[Link]("Each student object has 'id', 'name', 'locatio
n', 'phone', and 'courses' properties", function () {
var jsonData = [Link]();
[Link](function (student) {
[Link](student).[Link]('id');
[Link](student).[Link]('name');
[Link](student).[Link]('location')
;
[Link](student).[Link]('phone');
[Link](student).[Link]('courses');
});
});
Reponse time
[Link]("Response time is less than 200ms", function ()
{
[Link]([Link]).[Link](200
);
});
JSON SCHEMA
Day 7
Scripts
Pre-Request Scripts
Test-Scripts
Workflow
Pre-request script----- Request---Response--Tests
Collection
Folder
Request
Variables
What?
Why?
Where?
Scope
1. Global
2. Collection
3. Environment
4. Local
5. Data
Workspace ------ > Collection------- > Request
Global : Accessible in workspace (url_global)
Collection: Accessible within Collection (url_collect)
Environment: Accessible in all collections, but we need to switch to particular
environment (url_qa_env) (url_dev_env)
Local: Accessible only within request (specific to request)
[Link](“url_local”,”[Link]
Data: external files csv/text
Referring Variables {{variable}}
Creating Variables using pre-request script
Global Variable
[Link](“userid_global”,”2”);
Environment Variable
[Link](“userid_qa_env”,”2”);
Collection Variable
[Link](“userid_collect”,”2”);
Unset/Remove variables using script
Global Variable
[Link](“userid_global”);
Environment Variable
[Link](“userid_qa_env”);
Collection Variable
[Link](“userid_collect”);
Capture the values from variables
[Link]([Link](“userid_global”));
[Link]([Link](“userid_qa_env”));
[Link]([Link](“userid_collect”));
[Link]([Link](“url_local”));
Methods used
set – global, env, collection, local
unset - global, env, collection, local
get - global, env, collection, local
Data variables come from external files like CSV/ JSON
Usage of variables in request body
“name”:”{{name}}”,
“job”:”{{job}}”
Chaining of API’s
Student API
Run it locally on your machine and then start using it on postman
var jsonData=[Link]("responseBody");
Gorest API
URL: [Link] (But not endpoint)
POST /public/v2/users Create a new user
GET /public/v2/users/1 Get user details
PUT/PATCH /public/v2/users/1 Update User Details
DELETE /public/v2/users/1 Delete User
API Token (Use your own token cos this is automatically block)
6581f6970670548ec92ff62a29401bd2442f3357e26c99175ad02e
56cbe4f894
Request Body
“name”: “scott”,
“gender”: “male”,
“email”: “abc@[Link]”,
“status”: “inactive”
Email id should be different from one user
Chaining Process
Create User (POST)
{{URL}}/public/v2/users
Request Body
{
"name": "{{name_env}}",
"gender": "male",
"email": "{{email_env}}",
"status": "inactive",
"id": ""
}
Pre-Request script
var random=[Link](). toString(36).substring(2);
var useremail="jim"+random+"@[Link]";
var username="jim"+random;
[Link]("email_env", useremail);
[Link]("name_env", username);
To know/print values
[Link](useremail);
[Link](username);
Under Test Tab
Capturing ID from response and set as environment variable/ Parsing
Environment variable
var jsonData = [Link]();
var userId = [Link];
[Link]("userId", userId);
Get User Details (Get)
{{URL}}/public/v2/users/{{UserID}}
Tests Tab
Validating json fields in Response
[Link]("Status code is 200", function () {
[Link](200);
});
[Link]("Response has 'id' property", function () {
var jsonData = [Link]();
[Link](jsonData).[Link]("id");
});
[Link]("Response has 'name' property", function () {
var jsonData = [Link]();
[Link](jsonData).[Link]("name");
});
[Link]("Response has 'email' property", function () {
var jsonData = [Link]();
[Link](jsonData).[Link]("email");
});
[Link]("Response has 'gender' property", function () {
var jsonData = [Link]();
[Link](jsonData).[Link]("gender");
});
[Link]("Response has 'status' property", function () {
var jsonData = [Link]();
[Link](jsonData).[Link]("status");
});
Update User Details(PUT)
{{URL}}/public/v2/users/{{UserID}}
Request Body
{
"name": "{{name_env}}",
"gender": "male",
"email": "{{email_env}}",
"status": "active",
"id": ""
}
Pre-Request script
var random=[Link](). toString(36).substring(2);
var useremail="jim"+random+"@[Link]";
var username="jim"+random;
[Link]("email_env", useremail);
[Link]("name_env", username);
Delete Request
[Link](“userid”);
[Link](“email_env”);
[Link](“name_env”);
Next (Parameterization)
Books API
This api allows you to reserve a book
The api is available at [Link]
API Authentication
To submit/view your order you need to register your API client.
POST /api-clients/
The request body needs to be in json format and include the following properties
clientName – String
clientEmail – String
Example
“clientName”: “Postman”,
“clientEmail”: “valentin@[Link]”
The response body will contain access token. The access token is valid for 7 days.
Access Token:
“7ecf5a2fb972a29fffde48649f672812931732b49d68eb2080c65ae65fafaf19”
Possible errors
Status code 409 – “API client already registered.” Try changing the values for
clientName and clientEmail to something else.
Endpoints
GET /status
Returns the status of the API.
List of books
GET /books
Returns a list of books.
Optional query parameters:
type: fiction/non-fiction
limit: a number between 1 and 20
Get a single book
GET /books/ “bookId”
Retrieve complete information about a book
Submit an order
POST /orders
Allows you to submit an order. Requires authentication.
The request body needs to be in JSON format and include the following
properties.
bookId – integer – Required
customerName – String – Required
Example
POST /orders/
Authorization: Bearer <YOUR TOKEN>
{
“bookId”: 1,
“customerName”: “John”
}
The response body will contain the order id.
Order ID: “GW0ZuD3MOLE_PcjW4ZVqz”
Get all orders
GET /orders
Allows you to view all [Link] authentication.
Get an order
GET / orders/”orderId”
Allows you to view an existing order. Requires authentication.
Update an order
PATCH / orders/ :orderId
Update an existing order. Requires authentication.
The request body needs to be in JSON format and allows you to update the
following properties.
customerName – String
Example
PATCH /orders/PF6MF1PDcuhwobZcgm3y5
Authorization: Bearer <YOUR TOKEN>
{
“customerName”: “John”
Delete an oder
DELETE /orders/ :ordered
Deletes an existing order. Requires authentication.
The request body needs to be empty.
Example
DELETE /orders/PF6MF1PDcuhwobZcgm3y5
Authorization: Bearer <YOUR TOKEN>
API Data Driven Testing
Request type: POST
URL: [Link]
Request Body
{
"bookId":"{{BookId}}",
"customerName":"{{CustomerName}}"
}
Tests
[Link]("Status code is 201", function () {
[Link](201);
});
var jsonData=[Link](responseBody);
[Link]("orderid_env",[Link]);
BookI
D CustomerName
1 John
1 Kim
3 Scott
4 David
6 Mary
Request type: GET
URL: [Link]
Tests
[Link]("Status code is 200", function () {
[Link](200);
});
[Link]("check orderID present in the response body", function () {
var jsonData=[Link]();
[Link]([Link]).[Link]([Link]("orderid_env"));
});
Request type: DELETE
URL: [Link]
Tests
[Link]("Status code is 204", function () {
[Link](204);
});
[Link]("orderid_env");
Authorizations
Client ID: 08886c538486fbb8212f
Client Secret: a8e06b7bc3d72f42efc32084dfcd298534943faa
Swagger - interactive documentation
cURL - Client URL
curl -X GET "[Link] -H "accept:
text/plain; v=1.0"
Swagger documents
[Link]
[Link]
[Link]