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

R- Postman api

The document provides an overview of Postman, detailing its HTTP methods (POST, GET, PUT, PATCH, DELETE) and status codes, including client-side (400) and server-side (500) errors. It explains API testing, the features of Postman such as collections and environment variables, and how to handle authentication and response validation. Additionally, it covers automation of tests, debugging techniques, and the distinction between public and private APIs.

Uploaded by

rajat.kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

R- Postman api

The document provides an overview of Postman, detailing its HTTP methods (POST, GET, PUT, PATCH, DELETE) and status codes, including client-side (400) and server-side (500) errors. It explains API testing, the features of Postman such as collections and environment variables, and how to handle authentication and response validation. Additionally, it covers automation of tests, debugging techniques, and the distinction between public and private APIs.

Uploaded by

rajat.kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

POSTMAN

HTTP method-:
1. POST -: It is use to create a resource.
2. GET -: It is use to read or retrieve the resource.
3. PUT -: It is use for complete updating of the resource.
4. PATCH -: It is use for partial updating of the resource.
5. DELETE-: It is use to delete the resource.
Payload -: Pass the input details to API/body
Status code-:

100-: Continue
200-: Success
201-: Successfully created
204 -: Successfully deleted.
300-: Redirected
422 -: Cannot create repository with the same name.
429-: Too Many Requests
500-: Server-side error

1. Client-Side Errors (400 Status Codes)

Client-side errors occur when the client sends a request that the server cannot process due to
issues originating from the client.

These errors indicate something is wrong with the request, not the server.

Examples:

 400: Bad Request


The request is invalid.
Example: Sending a POST request with a missing or invalid JSON body.
 401: Unauthorized
The client has not provided valid authentication credentials.
Example: Missing or invalid API token.
 403: Forbidden
The server understood the request but refuses to authorize it.
Example: Trying to access restricted resources without proper permissions.
 404: Not Found
The requested resource or endpoint does not exist.
Example: Using an incorrect URL or accessing a non-existent API.
 422: Unprocessable Entity
The server understands the request but cannot process it due to logical errors.
Example: Attempting to create a record that violates validation rules (e.g., duplicate
email).

Examples of Clients

1. Postman: Used to manually send API requests and analyze responses during testing.
2. Web Browser: Sends requests for web pages and retrieves responses.
3. Mobile Apps: For example, a weather app requesting data from a weather API.
4. Backend Systems: A payment gateway interacting with a bank’s API.

Key Features of Client-Side Errors:

1. Who is Responsible?
The client is responsible for fixing the issue by correcting the request.
2. When Does It Happen?
It happens when the client:
o Sends incorrect or incomplete data.
o Uses invalid endpoints or HTTP methods.
o Wrong authentication.

2. Server-Side Errors (500 Status Codes)

Server-side errors occur when the server fails to process a valid request due to an issue on
the server side. These errors indicate problems with the server or the API logic.

Examples:

 500: Internal Server Error


The server encountered an unexpected issue and could not complete the request.
Example: A database connection failure or unhandled exception in the server code.
 502: Bad Gateway
The server acting as a gateway received an invalid response from the upstream server.
Example: Issues with a load balancer or proxy server.
 503: Service Unavailable
The server is temporarily unable to handle requests, often due to maintenance or
overload.
Example: API downtime during server upgrades.
 504: Gateway Timeout
The server acting as a gateway didn’t receive a timely response from the upstream
server.
Example: Slow response from a database.

Key Features of Server-Side Errors:

1. Who is Responsible?
The server owner or developer is responsible for fixing the issue by addressing server-
side bugs.
2. When Does It Happen?
It happens due to:
o Server misconfiguration.
o Unhandled exceptions in the application logic.
o Network or database failures.

Comparison:
Aspect Client-Side Errors (400) Server-Side Errors (500)

Problem in the request sent by Problem in the server's ability to process the
Origin of Issue
the client. request.

Server-side developer/administrator needs to


Responsibility Client needs to fix the request.
fix the issue.

Missing parameters,
Examples Database failure, application crashes.
unauthorized access.

Common Status
400, 401, 403, 404, 422 500, 502, 503, 504
Codes

Q. What is Postman, and what are its primary features?


Postman is a collaboration platform for API development and testing.
It provides a user-friendly interface to build, test, document, and share APIs.
Main features are:
 Collections: Organize requests into groups.
 Environment Variables: Manage different setups for development,
staging, and production environments.
 Pre-request Scripts and Tests: Automate tests and pre-processing of
requests.
 Monitors: Schedule and automate API testing.
 Postman Console: Debug and view request logs.
 API Documentation: Auto-generate documentation from collections.
Q. What is API testing?
Testing the interface between two applications or programs is called as
API testing.
Q. Why API testing is necessary?
In order to make sure the connection or the interface is working as
expected with respect to the functionality, performance, security etc…
When API testing has to be performed?
i. In the absence of user interface.
ii. API testing is done before manual testing.
iii. API testing has to be done in order to test all the web service.
Q. How do you create a new request in Postman?
 Open Postman and click "New" > "Request".
 Choose the HTTP method (GET, POST, PUT, DELETE, etc.).
 Enter the API endpoint (URL).
 Optionally, we can add headers, authorization, request body, and
parameters.
 Click "Send" to execute the request and see the response.
Q. What are collections in Postman?
Collections are used to organize and group API requests. They allow users to:
 Structure related requests in folders.
 We can save and reuse requests across different environments.
 We can share and export the collection with others for collaboration.
 We can automate requests using the Collection Runner.
Q. What is a Postman Environment Variable, and how do you use it?
Here we can store values (like Base URLs or authentication tokens) that can be
reused across multiple requests.
We can set variables by:
 Creating an environment under Manage Environments.
 Defining key-value pairs.
 Using the variable in our request by using double curly braces:
{{variableName}}.
We can also set dynamic variables in pre-request scripts.
Q. How can you handle authentication in Postman?
Postman supports various authentication mechanisms:
 Basic Authentication: Use username and password in the Authorization
tab.
 API Key-:
Bearer Token: Use a static or dynamic token in the Authorization tab.

Q. Explain how to use a Bearer Token in Postman?

 First, I make sure I have the Bearer Token, either from an API login or
an authentication endpoint. [ Query parameter and path parameter ]
 In Postman, I create a new request, set the request method (like GET
or POST), and enter the API URL.
 I then go to the Authorization tab, select Bearer Token from
the dropdown, and paste the token in the field provided.
 After that, when I hit Send, Postman automatically adds the token in
the Authorization header as Bearer <token>.
API Key: Add API keys directly to the request as a query parameter or header.

Authentication can also be dynamically set in pre-request scripts using:


pm.request.headers.add({key: "Authorization", value: "Bearer " +
token});

Q. What are Newman and the Postman Collection Runner?


 Newman is a command-line tool used to run Postman collections
outside the Postman app, allowing for CI/CD integration.
 The Postman Collection Runner is a built-in feature that allows us to
run collections within the Postman app, enabling batch execution of
requests.
Q. How do you handle response validation in Postman?
 We can handled by writing test scripts in JavaScript within the
Tests tab.
 These scripts can check status codes, response times, and
response bodies to ensure they meet expected criteria.
Q. What are global variables in Postman and how do you use
them?
 Global variables are variables that can be accessed across all
collections, environments, and requests within Postman.
 They are useful for storing values that are reused across
different contexts, such as base URLs or authentication tokens.
Q. Whether an API is public or private:
1. To determine if an API is public or private, I need to check the
documentation for access requirements and authentication
methods.
2. If it's openly accessible and widely documented, it's public.
3. If it's restricted and requires special access permissions, it's private.
Public API
 Public APIs are usually well-documented and accessible to everyone.
 Public APIs might use simple authentication methods like API keys.
 Public APIs are often listed on the provider's website or
public directories.
 Public APIs will have openly published terms of service and usage limits.
Private API
 Private APIs often require specific credentials or permissions to
access their documentation.
 Private APIs generally implement stronger authentication, such as
OAuth tokens, and restrict access to authorized users only.
 Private APIs aren't advertised and are typically used internally or
with specific partners.
 Private APIs are usually governed by internal policies or agreements
with specific partners.

Q. What are Postman Collections and Monitors, and how do they work
together?
 Collections are groups of API requests that can be run together or
individually.
 Monitors are used to schedule automated runs of these collections at
specific intervals (e.g., hourly, daily). They allow you to:
 Continuously check the health of your APIs.
 Receive alerts when a request fails.
 Monitor can be set up from the Postman collection page with integrated
test scripts for automated validation.

Local API creating process -:


Command line in command prompt -:
 Check node version -: node - -version
 Check npm version -: npm - - version

 1st -: json-server
 2nd -: npm install -g json-server
 3rd -: json-server data.json

Q. How can you automate tests in Postman?


Write JavaScript code in the Tests tab to automatically validate responses.
We can add assertions to check status codes, response times, and specific data
in the response. For example:

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


pm.response.to.have.status(200);
});
pm.test("Successful GET request", ()=>{
pm.expect(pm.response.code).to.be.oneOf([200,201]);
});

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


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

Q. How do you test an API endpoint that requires a JSON payload?


Set the request method to POST (or PUT, PATCH).
In the Body tab, select raw and choose JSON format.
Write the JSON payload in the editor.
{
"FirstName": "Rajat",
"LastName": "Pradhan",
"Job": "QA"
}
Click Send to execute the request, and validate the response in the Tests tab
using assertions.

Q. Imagine you have an API that returns a list of users. How would you
validate that the response contains the expected data?

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


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

pm.test("Response is an array", function () {


pm.expect(pm.response.json()).to.be.an('array');
});

pm.test("First user is John", function () {


var jsonData = pm.response.json();
pm.expect(jsonData[0].name).to.eql("John");
});

Q. Describe how you would debug an API request that is returning an error.
 Check the status code: Ensure the correct endpoint and HTTP method
are used.
 Inspect headers: Look at Authorization, Content-Type, and other
required headers.
 Examine the request payload: Ensure correct JSON or form data is sent.
 Use Postman Console: View the request logs, including headers and full
payload.
 Run in Collection Runner: Repeat the request and verify logs/output.

Q. To set up API testing, I follow these steps:


 Install the tool— Download Postman or add Rest Assured dependencies
in Maven for Java projects.
 Define the API endpoints, including the base URL, specific endpoints,
HTTP methods (like GET, POST), and any necessary parameters such as
headers or query parameters.
 Set up authentication if needed—using methods like OAuth, Bearer
Tokens, or Basic Authentication.
 Configure the API request by specifying the HTTP method, adding the
URL, headers (like Content-Type), and the request body for methods like
POST or PUT.
 Send the request and verify the response by checking the status codes
(e.g., 200 OK), response body, headers, and response time.

Testing the Status code for GET-:

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


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

pm.test("Successful GET request", ()=>{


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

Testing the Header Response-:


pm.test("Content-Type header is present", ()=>{
pm.response.to.have.header("Content-Type");
});

/*
pm.test("Content-Type header is application/json", ()=>{
pm.expect(pm.response.headers.get('Content-Type')).to.eql
('application/json; charset=utf-8');
});*/
Testing the Cookies response-: We can verify them by their value and
presence of coolies.

pm.test("Cookies 'language' is present", ()=>{


pm.expect(pm.cookies.get('language')).to.be.true;
});

Asserting a value type


Test the type of any part of the response:
{
"id": "02c4",
"name": "Rajat Kumar",
"location": "India",
"mobile": "34876598",
"designation": [
"SDET",
"Automation"
]
}

// Test the type of any part of the Response


const jsonData = pm.response.json();

pm.test("Test data type of the response", ()=>{


pm.expect(jsonData).to.be.an("array");

jsonData.forEach((item) => {
pm.expect(item).to.be.an("object"); // Each item
should be an object
pm.expect(item.id).to.be.a("string");
pm.expect(item.name).to.be.a("string");
pm.expect(item.location).to.be.a("string");
pm.expect(item.mobile).to.be.a("string");
pm.expect(item.designation).to.be.an("array"); //
Check if designation is an array
});
});
Assertion array properties -:
Check if an array is empty and if it contains particular items
pm.test("Test array properties", ()=>{
pm.expect(jsonData).to.be.an("array");

jsonData.forEach((item) => {
pm.expect(item.designation).to.have.members(["QA","SDET"])
;
});
});
Validate JSON field in response
{
"id": "02c4",
"name": "Rajat Kumar",
"location": "India",
"mobile": "34876598",
"designation": [
"SDET",
"Automation"
]
}
Validate JSON Schema
We need to genearate schema file, then need to save in a variable
like var or const. Then validate using tv4
tv4 – tini validator version number 4 -: (postman library )
Generate JSON Schema -: https://jsonschema.net/
var Schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": {
"type": "object",
"required": ["id", "name", "location", "mobile",
"designation"],
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"location": {
"type": "string"
},
"mobile": {
"type": "string"
},
"designation": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}

pm.test("Schema is validate", ()=>{


pm.expect(tv4.validate(jsonData, Schema)).to.be.true;
})

Scripts-:
 Pre-request scripts
 Tests
Pre-Request script  Request  Response  Tests
 Collection
 Folder
 Request
Variable -:
 Global -: Accessible in workspace
 Collection-: Accessible within collection
 Environment-: Accessible in all collections, but we need to
switch to particular environment.
 Local variable -: Accessible only within request (specific to
request)
 Data variable -: External files csv/text
Referring variable using -: {{variable_name}}
Chaining of API’s-: Response from one API and request for another
API
GoRest API-:
URL-: https://gorest.co.in/
Token -: 612fb2ef78fcac307cd3a3bff004d80a511f1cfe79cda744f65c1a585eed2761

POST -: Create a new user

GET /public/v2/users/6942511 -: Get user details

PUT|PATCH /public/v2/users/6942511 -: Update user details

DELETE /public/v2/users/6942511 -: Delete user

Request Body-:

{
"id": 7537304,
"name": "Datta Chaturvedi DC",
"email": "[email protected]",
"gender": "female",
"status": "active"
}
POST Create user
Pre-request script
var random = Math.random().toString(36).substring(2);
var userEmail = "jhon"+random+"@gmail.com";
var userName = "Jhon"+random;

pm.environment.set("email_env", userEmail);
pm.environment.set("name_env", userName);
Post-request script
var jsonData = pm.response.json();
pm.environment.set("userid_env", jsonData.id);

pm.test("The status should be 201", () => {


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

GET user details


Post-request script
var jsonData=pm.response.json();

pm.test("Value of json field", ()=>{


pm.expect(jsonData.id).to.eql(pm.environment.get("userid_env"));
pm.expect(jsonData.name).to.eql(pm.environment.get("name_env"));
pm.expect(jsonData.email).to.eql(pm.environment.get("email_env")
);

})

PUT update details


Pre-request
var random = Math.random().toString(36).substring(2);
var userEmail = "kamilin"+random+"@gmail.com";
var userName = "Kamilin"+random;

pm.environment.set("email_env", userEmail);
pm.environment.set("name_env", userName);
Post request
var jsonData=pm.response.json();

pm.test("The status should be 200", () => {


pm.response.to.have.status(200);
});
DELETE user
Post response
pm.test("Status should be 204", ()=>{
pm.response.to.have.status(204);
})

pm.environment.unset("email_env");
pm.environment.unset("userEmail");
pm.environment.unset("userName");

BOOKs API-:
"accessToken":
"44abc663cbeb49112913d91abbadb2b7d39cd94510e798842c584a3c69809c61"

You might also like