Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

API Testing

Uploaded by

mk31875
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

API Testing

Uploaded by

mk31875
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

API Testing

Types of API

API
Google FaceBook
REST API Methods / http request

1. get
2. post
3. put
4. delete

http://www.google.com/
https://reqres.in/api/users?page=2

https://reqres.in/api/users/2

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

https://reqres.in/api/users?page=2

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: http://nodejs.org/en/download/
Environment Variable
2) Check node and npm versions (npm comes along with node.js)

node –version
npm --version
3) Install json server
npm install –g json-server
4) json-server student1.json

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

pm.test (“Test Name”, function()

//assertion;

);

pm.test (“Test Name”, () =>

//assertion;

);

Testing Status Codes


Test for the response status code:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});

If you want to test for the status code being one of a


set, include them all in an array and use of

pm.test("Successful get request", function () {


pm.expect(pm.response.code).to.be.oneOf([200, 201])
;
});

Check the status code text:

pm.test("Status code has string", function () {


pm.response.to.have.status("Created");
});

pm.test("Response status code is 201", function () {


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

Testing Headers

Check that response header is present;

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


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

Test for response header having a particular value;

pm.test("Content-Type header is application/json", func


tion () {
pm.expect(pm.response.headers.get("Content-Type"))
.to.eql('application/json; charset=utf-8');
});

Testing Cookies

Check that response header is present;

pm.test("Content 'language' is present", function () {


pm.response.to.have.header("Cookies");
});

Test for response header having a particular value;

pm.test("Cookie 'language' has value 'en-gb'", function


() {
pm.expect(pm.response.headers.get("Cookies")).to.eq
l("en-gb");
});

Testing Response Data


pm.test("Each student object has 'id', 'name', 'locatio
n', 'phone', and 'courses' properties", function () {
var jsonData = pm.response.json();
jsonData.forEach(function (student) {
pm.expect(student).to.have.property('id');
pm.expect(student).to.have.property('name');
pm.expect(student).to.have.property('location')
;
pm.expect(student).to.have.property('phone');
pm.expect(student).to.have.property('courses');
});
});
Reponse time
pm.test("Response time is less than 200ms", function ()
{
pm.expect(pm.response.responseTime).to.be.below(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)

pm.variables.set(“url_local”,”https://reqres.in”);
Data: external files csv/text

Referring Variables {{variable}}

Creating Variables using pre-request script

Global Variable

pm.globals.set(“userid_global”,”2”);

Environment Variable

pm.environment.set(“userid_qa_env”,”2”);

Collection Variable

pm.collectionVariables.set(“userid_collect”,”2”);

Unset/Remove variables using script

Global Variable

pm.globals.unset(“userid_global”);

Environment Variable

pm.environment.unset(“userid_qa_env”);

Collection Variable

pm.collectionVariables.unset(“userid_collect”);

Capture the values from variables

console.log(pm.globals.get(“userid_global”));

console.log(pm.environment.get(“userid_qa_env”));

console.log(pm.collectionVariables.get(“userid_collect”));

console.log(pm.variables.get(“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=JSON.parse("responseBody");

Gorest API

URL: https://gorest.co.in (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@gmail.com”,

“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=Math.random(). toString(36).substring(2);

var useremail="jim"+random+"@gmail.com";
var username="jim"+random;

pm.environment.set("email_env", useremail);
pm.environment.set("name_env", username);

To know/print values

console.log(useremail);

console.log(username);

Under Test Tab

Capturing ID from response and set as environment variable/ Parsing


Environment variable

var jsonData = pm.response.json();


var userId = jsonData.id;
pm.environment.set("userId", userId);
Get User Details (Get)

{{URL}}/public/v2/users/{{UserID}}

Tests Tab

Validating json fields in Response

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


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

pm.test("Response has 'id' property", function () {


var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("id");
});

pm.test("Response has 'name' property", function () {


var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("name");
});

pm.test("Response has 'email' property", function () {


var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("email");
});

pm.test("Response has 'gender' property", function () {


var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("gender");
});

pm.test("Response has 'status' property", function () {


var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("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=Math.random(). toString(36).substring(2);

var useremail="jim"+random+"@gmail.com";
var username="jim"+random;

pm.environment.set("email_env", useremail);
pm.environment.set("name_env", username);

Delete Request

pm.environment.unset(“userid”);

pm.environment.unset(“email_env”);

pm.environment.unset(“name_env”);

Next (Parameterization)

Books API
This api allows you to reserve a book

The api is available at https://simple-books-api.glitch.me

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@example.com”

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 orders.Requires 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: https://simple-books-api.glitch.me/orders

Request Body

{
"bookId":"{{BookId}}",
"customerName":"{{CustomerName}}"
}
Tests

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


pm.response.to.have.status(201);
});
var jsonData=JSON.parse(responseBody);
pm.environment.set("orderid_env",jsonData.orderId);

BookI
D CustomerName
1 John
1 Kim
3 Scott
4 David
6 Mary

Request type: GET

URL: https://simple-books-api.glitch.me/orders/{{orderid_env}}

Tests

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


pm.response.to.have.status(200);
});
pm.test("check orderID present in the response body", function () {
var jsonData=pm.response.json();
pm.expect(jsonData.id).to.equal(pm.environment.get("orderid_env"));
});

Request type: DELETE

URL: https://simple-books-api.glitch.me/orders/{{orderid_env}}

Tests

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


pm.response.to.have.status(204);
});
pm.environment.unset("orderid_env");

Authorizations
Client ID: 08886c538486fbb8212f

Client Secret: a8e06b7bc3d72f42efc32084dfcd298534943faa

Swagger - interactive documentation

cURL - Client URL


curl -X GET "https://fakerestapi.azurewebsites.net/api/v1/Books" -H "accept:
text/plain; v=1.0"

Swagger documents

https://fakerestapi.azurewebsites.net/index.html

https://petstore.swagger.io/

https://httpbin.org/#/

You might also like