Automation QA Testing Course Content

API Automation Testing With Rest Assured


1.What is Client and Server?

A server is a connection point for several clients , that will handle their requests. A client is software that (usually) connects to the server to perform actions. The client provide a user interface that allows users to carry out actions.

2. What is Presentation, Business & Database

Layer



What is an API? Can you give some Examples?

What is API Testing?

Ans: API testing is a type of software testing that focuses on verifying and validating the functionality, performance, and reliability of Application Programming Interfaces (APIs). An API is a set of rules and protocols that allows different software applications to communicate and interact with each other. API testing helps identify issues such as incorrect data formats, incorrect response codes, security vulnerabilities, performance bottlenecks, and functional errors.

  • The term API was first mentioned in the article “The Relational and Network Approaches: Comparison of the Application Programming Interface” published by Christopher J. Date in 1974.
  • API, which stands for Application Programming Interface, is a software tool that allows 2 software to communicate with each other.
  • APIs are used with protocols such as HTML, XML and JSON. HTML is used for web-based APIs, XML is used for SOAP APIs, and JSON is used for Rest APIs.
  • Many data can be easily retrieved via APIs on the web or on smartphones, without the need to re-create an infrastructure. In this way, there is no need for a new program, communication is handled practically and quickly.
  • The API also creates a firewall for users. Instead of sharing all your data with the application’s shared server, you only send a single request to the server via API, ensuring full security of your data. In this respect, the API also acts as a key.

What are some advantages of APIs?

The main ones are as follows:

  • Applications: Access to APIs ensures more flexibility in information-transfer processes.
  • Reach: APIs let you create layers in apps in order to distribute information to different audiences.
  • Customization: Furthermore, it can serve as a solution to create different experiences for users, letting protocols, functions, and commands be adapted according to specific demands.
  • Efficiency: When you have content that is automatically published and made available on different channels simultaneously, APIs allow for more efficient data distribution.
  • Adaptability: One of the greatest benefits of APIs is the ability it has to adapt to changes through data migration and flexibility of services.

Where is API Used?

Since APIs enable communication between the client and the server, they are used for various purposes in most web and mobile applications. API usage areas are as follows.

.When allowed to sign in to apps that use social media credentials

.While retrieving your data from Facebook servers

.When contacting the bank while making payments in e-commerce transactions

.In weather apps

.In applications where instant stock market data is monitored

.Distributing software updates to applications

.Providing location data




Most Popular API Services and Some Useful APIs

Google API: These are the APIs that Google offers to retrieve data from its own applications and websites. They provide the opportunity to combine services provided by Google, such as Analytics, Adsense and Google search, with your own project. You can review the APIs offered by Google here.

Whatsapp API: It is an API service for adding a Whatsapp button to the website. With WhatsApp Business API, you can create a company profile, send messages and receive messages using the APIs with the integration you want. You can also create and use message templates as you wish.

Facebook API: It is an API for adding a Facebook button to the website and connecting with Facebook. Facebook Api Key is a key that allows developers to add like and send buttons to the website.

Youtube API: Youtube API allows accessing YouTube channel data. They are APIs that allow you to bring the YouTube experience to a web page, app or device.

What are the API Types?

APIs are classified according to their usage patterns and architectures.

API Types According to Purposes of Use

Internal API: It is a type of API that is used only by certain people and is hidden from external users. This type of API is defined for specific departments of the company and is hidden from third parties. It is mostly used for reuse and production.

Open API: APIs that are open to developers and everyone else. They are also known as publicly available or Public APIs. It is divided into two: paid and free.

Partner API: APIs that enable the systems of companies that conduct business with a certain business partnership to coordinate in their joint operations are called Partner APIs. They are not open to everyone. For example, communication between an e-commerce site and a cargo company is done using Partner API.

Composite API: Composite APIs are APIs that combine multiple data or service APIs, allowing developers to access several endpoints in a single call.



API examples:
Google Maps API, Amazon Advertising API, Twitter API, YouTube API, etc.

For example, you are using an API when paying for your new clothes online with a credit card. The Ecommerce platform sends you to your bank’s website to confirm the card data, and then right back.

What is Web Service?

A Web Service is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network".
 for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML/JSON messages over HTTP protocol.

S.No
Web-Service
API
1
All Web Services are API.

All API are not web services.
2
Web service uses only three styles of use: SOAP, REST and XML-RPC for communication.

API may use any style for communication.

3
Web Services are self-contained.
API are open source and can be used anywhere.

4
It can only be hosted on IIS(Internet Information Service).

It can be hosted within application or IIS.
5
Web Service might not perform all operation that an API would perform.

API can perform all task that Web service can do.
6
It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

It is light-weight architecture and good for devices which have limited bandwidth, like mobile devices.
7
It needs network for its operation.

API does not need network for its operation.

 What is API Testing?


API testing is a kind of software testing which determines if the developed
APIs meet expectations regarding the functionality, reliability, performance,
and security of the application.


What are the advantages of API Testing?

API testing provides access to the application without a user interface. The core and

code level of functionalities of the application will be tested and evaluated early

before the GUI tests. This will help detect the minor issues which can become

bigger during the GUI testing.

API testing usually is less time-consuming than functional GUI testing.

API test automation requires less code so it can provide better and faster test

coverage compared to GUI test automation.

In API testing, data is exchanged using XML or JSON. These transfer modes are

completely language-independent, allowing users to select any code language when

adopting automation testing services for the project.

APIS commonly uses  webhooks to notify other systems


What are differences between API Testing and Unit Testing?


What are features of web services?
Interoperability
Reuse already developed(old) functionality into newsoftware
Loosely Coupled 
Extensibility

What are different types of web services?

      

REST vs. SOAP APIs: Key Differences and Uses

Today, REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) APIs stand out as two widely used protocols in software development processes. In this article, we will examine the main differences and usage areas of REST and SOAP.

1. Key Differences:

Data Format:

REST: Uses lightweight data formats such as JSON (JavaScript Object Notation) or XML (eXtensible Markup Language). JSON is generally the preferred format and has a more readable, lightweight structure.

SOAP: It is an XML-based protocol. It generally uses XML for data transfer, which is a heavier data structure.

Protocol and Standards:

REST: Works on HTTP protocol. Standards are usually determined at the application level and REST has a stateless structure.

SOAP: It uses its own protocol and usually transfers data using other communication protocols such as HTTP, SMTP or TCP. Standards are generally set by organizations such as W3C (World Wide Web Consortium) and OASIS (Organization for the Advancement of Structured Information Standards).

Communication Model:

REST: It has a client-server based communication model and each request is stateless. This allows for easier scaling between applications.

SOAP: It is often used in business-to-business integrations and supports different communication models such as client-server, publish-subscribe or peer-to-peer.

2. Areas of Use:

REST:

. Ideal for web applications, especially single page applications (SPA).

Its lightweight and simple design supports mobile application development.

.RESTful APIs typically use URLs that represent resources and interact with HTTP methods.

SOAP:

It is widely used in large business-to-business systems and especially in industries such as finance, healthcare and telecommunications.

It is suitable for complex transactions with security and integrity requirements.

It defines how to use the API using WSDL (Web Services Description Language) and has a more rigid contractual structure.



What is SOAP?

SOAP stands for Simple object access protocol. It is protocol to exchange information using request and response in XML format over transport protocol such as HTTP, SMTP etc


What are important components for SOAP?

  • Simple access object protocol (SOAP)
  • Web Services Description Language (WSDL)
  • Universal Description, Discovery and Integration(UDDI)

What is WSDL?

WSDL stands for Web Service Description Language. It is an XML file that describes the technical details of how to implement a web service, more specifically the URI, port, method names, arguments, and data types. You can understand following details using WSDL 
  •     Port / Endpoint – URL of the web service
  •     Input message format
  •     Output message format
  •     Security protocol that needs to be followed
  •     Which protocol the web service uses

What is UDDI?

UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web service provider can register themselves with a UDDI and make themselves available through it for discovery

SOAP Testing Tools:

1)SOAP UI
2)UFT
3)JMETER

RESTful web service:

REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis.
REST (Representational State Transfer) provides communication between the client (usually a browser) and the server using ordinary HTTP requests (GET, POST, PUT, DELETE, etc.). It transfers information from the client in the request parameters, information from a server in the body of the response (which can be, for example, a JSON object or an XML document).

REST is a software architectural style for web services. Actually, it is not a protocol itself, but a set of rules or guidelines for building an effective communication model between the sender and receiver of information. RESTful Web services are built with a list of constraints that simplify client-server information exchange and their software implementation.

REST API works over HTTP protocol. RESTful service uses four methods from HTTP protocol: get, post, put, and delete. These methods are restricted to storing client status on the state server, i.e. “stateless”.

In turn, HTTP (HyperText Transfer Protocol) is an application-level data transfer protocol that was originally planned in the form of hypertext documents in the HTML format and is currently used to transfer arbitrary data. The basis of HTTP is the client-server technology, that is, the following are assumed:

  • Consumers (customers) who initiate a connection and send a request;
  • Providers (servers) who are waiting for a connection to receive a request, take the necessary actions, and return a message with the result.

The RESTful application builds logic around resources, but not around endpoints:

  • Architectural style with no standardized description.
  • Stateless (no server-side information about client state).
  • A cache is available for API calls.
  • One presentation layer works with JSON, XML, HTML, etc.
  • Works well on the public API level, microservices, and systems with high scalability




  

The Difference between Authentication and Authorization

Understanding the Role of Parameters/Headers in REST API Design

Both terms will come to mind when talking about securing applications. And yet, there might be people that confuse the meaning of these terms
In the authentication process, the identity of the user is checked to provide access to the system. This process verifies ‘who you are?’ so the user needs to supply login details to authenticate.
Authorization is the process of verifying if the authenticated user is authorized to access specific information or be allowed to execute a certain operation. This process determines which permissions the user has.


OAuth2.0 Token :



Resource

A resource in a REST API is a unique identifier for a data object that can be accessed and manipulated through the API using a set of standardized methods.

Format of REST API URI: The format of a REST API URI (Uniform Resource Identifier) typically follows a hierarchical structure that consists of several parts

  1. Protocol: Protocol is used to access the resource, such as HTTP or HTTPS. It is typically included at the beginning of the URI, before the colon symbol.
  2. Host: The host specifies the domain name or IP address of the server that hosts the resource. It is typically included after the protocol and the colon symbols.
  3. Port: The port specifies the network port number used for the communication. It is usually optional and included after the host and the colon symbols.
  4. Resource- Path: The path specifies the location of the resource within the server’s file system hierarchy. It is typically included after the host and the port, and separated from the previous parts by a forward slash symbol.
  5. Parameters: Query/Path parameters provide additional information about the request, such as search filters or pagination details or point to a specific resource within a collection. They are usually included after the path and separated from it by a question mark(Query params) and by /(Path params) symbol.

Format of URI

Protocol://BaseURL+Resource+Path/Query Parameters

Below is an example of the URI structure.






Parameters

If your API is expecting any parameters, then you must pass those parameters as part of your request.

We have two types of parameters

  1. Path Parameters
  2. Query Parameters

Path Parameters

Variable part of the URL path. These are embedded in the URL path of a request. Path parameters are used to point to a specific resource within a collection. Path parameters are part of the URL only. Let’s take an example of REST API for managing books.

GET: /books/2324

Here “2324” is a Path parameter that identifies a specific book by its unique identifier.

The server uses it to retrieve the corresponding book from a database. Path parameters are a simple and intuitive way to pass data to a REST API, and they are widely used in real-world APIs.

Query Parameters

query parameters are a way to pass additional information to a server by appending it to the end of a URL. Query parameters are typically used to filter, sort, or paginate a list of resources returned by a server. Let’s take the same Rest API for managing the books.

GET /books?author=Ruskin+Bond&limit=10

In this example, “author” and “limit” are query parameters. The server can use this information to filter the list of books by the specified author and limit the number of books returned to 10.

Query parameters are indicated in a URL by adding a question mark (?) after the base URL, followed by one or more key-value pairs separated by ampersands (&). Query params are easy to use and understand, as they follow a simple key-value format.

Headers/Cookies

Headers and cookies are the mechanisms for sending additional/meta-data information along with a request or a response. They provide information such as the content type, authentication credentials, and cache-control directives. The headers are represented as key-value pairs in the HTTP request/response.

Cookies are also a type of header that is used to store small amounts of data on the client side, typically in the web browser. Cookies are sent from the server to the client in the response headers, and the client stores them locally. The client then sends the cookie back to the server in subsequent requests, allowing the server to identify and track the client’s activity over subsequent sessions.

Conclusion

Finally, developers should be aware that headers and parameters are not a replacement for proper API design, but rather a complementary feature that can help make APIs more effective. By following best practices for REST API design and using headers and parameters appropriately, developers can create APIs that are more flexible, powerful, and user-friendly.




Which REST constraint essentially prohibits the use of cookies?

Ans)stateless

What is a URI?

A URI, which stands for Uniform Resource Identifier, is a sequence of characters that identifies a web resource by location, name, or both in the World Wide Web. It is a method that allows for the uniform identification of the resources. Basically, there are two types of URIs: URNs (Uniform Resource Names) and URLs (Uniform Resource Locators).

Example: URN:ISBN:0-452-12776-411133

Tel:+1-855-287-1222

  1. mailto:hey.Doe@example.com
  2. news:comp.infosystems.www.servers.unix
  3. urn:oasis:names:specification:docbook:dtd:xml:4.1.2

What is a URL?

On the other hand, a URL, which is a short form for Uniform Resource Locator, is a sequence of characters that identifies the network location of a resource.  Besides identifying a resource, URLs help locate a resource by describing its primary access location. An URL starts with HTTP/https when the resource is web type data, mailto if the resource is an email address, or FTP if the resource is a file.  The syntax of a URL is as follows: http://www.sites.com/file/filename.jpg.

Example: https://www.travel.com




URIURL
Resource identifierResource locator
Superset of URLType of URI
It is often utilized in XML  and tag library files such as JSTL and XSLT to identify resources and binaries.Often used to find webpages
Its primary purpose is to identify a resource and differentiate it from other resources either by using location, name  or bothIts primary goal is to get the address or location of a resource
The scheme can be anything from protocol to designation and specificationThe scheme is usually a protocol such as https, HTTP, FTP, and LDAP, among others

What is Resource?

Resource is a physical or virtual component, which supports/extends/represents/constructs a system. Consider a real time example of Motor Bike. Wheels, breaks, headlight, fuel tank etc all are resources of a Motor bike. All resources have names, location and identifiers.

Take another example of Google. Now append “/maps” in last of base url “https://www.google.com/” as “https://www.google.com/maps“. Google will launch Google Maps. Try same with “/news”. Google will launch Google News. Here “Maps” and “News” are actually resources which has its names and locator.

What are the different methods in API Testing?

Ans:

  1. GET: Get is used to retrieve data stored on the server. GET method does not have a request body.

2. POST: Post method is used when you want to create a new record on the server. Post method used a request body.

3. PUT: PUT is used to update the existing resource server, It modifies the existing resource. If the resource does not exist then it creates the resource. In PUT we need to pass the whole body in the request

4. DELETE: Delete is used to delete any record from the server.

5. PATCH: PATCh is also used to partially modify the existing resource. For eg, If you want to update only the address of the resource Then we use PATCH. In the Patch request body, we will pass only those parameters which you want to modify.

When do we use PUT and PATCH?

Ans: PUT is used to replace the entire resource on the server. For eg. In the below Eg. If you want to update all the details except Email then you can use PUT and in the request body, we will pass everything except Email.

{

id: 1,

email: rameshn33@gmail.com ,

city: Phoenix,

phone: +16232733578

}

Now If you want to update only the email address then we can use PATCH and will pass only the email address parameter in the request body.

{

email: rameshn33@gmail.com

}



What are the different response codes in API Testing?

Ans: List of commonly used Status codes

200 — OK, When the request is successful.

201: Created, The request has been fulfilled, resulting in the creation of a new resource

202: Accepted, The request has been accepted for processing, but the processing has not been completed yet.

400 — Bad Request, These are Client-side errors. And the server cannot process the request because the request is not formatted properly.

401=Unauthorized, This status code is received when authentication is required and the user has failed or has not yet been provided yet.

403- Forbidden, This error is received when the user is authorized but is not authenticated for the requested resource.

404- Not Found, This code is received when the requested resource is not found

405- Method Not Allowed, This code is received when the request method is not supported for the requested resource;

408 Request Timeout. The server timed out waiting for the request.

500 — Internal Server error, These are Server side errors. This is received when an unexpected condition has encountered

502- Bad Gateway. This is received when the server which was acting as a gateway has received an invalid response from the upstream server.

503- Service Unavailable. This is received when the server is not available to process the request.

504- Gateway Timeout. When the server did not receive a timely response from the upstream server.



The HTTP OPTIONS method is used to request information about the communication options available for the target resource. The response may include an Allow header indicating allowed HTTP methods on the resource, or various Cross Origin Resource Sharing headers.26-Nov-2016


The HEAD method is identical to GET except that the server MUST NOT return a message-body
 in the response.
Understanding REST URL and Method:
What is the differene between path parameters and query parameters and provide examples?

Path parameters and query parameters are both ways to pass data in a URL in web APIs, but they are used for different purposes:

  1. Path parameters: They are used to identify a specific resource within a collection of resources. For example, in a RESTful API, you might use a path parameter to specify the unique identifier of a user, like this: /users/{id}, where {id} is a path parameter that represents the unique identifier of the user.

  2. Query parameters: They are used to provide additional information or to filter the results of a resource collection. For example, in a RESTful API, you might use a query parameter to specify the number of results to return, like this: /users?limit=10, where "limit" is a query parameter.

  3. Examples:

    Path parameter:

    • /users/{id} - Returns details of a specific user with the given id.
    • /posts/{id}/comments - Returns comments for a specific post with the given id.
    • Query parameter:

      • /users?limit=10 - Returns a list of 10 users.
      • /posts?category=news&sort=desc - Returns a list of posts sorted in descending order by category "news".

Best Practices for Handling JSON Request Bodies in POST API Calls

What is a POST request?

A POST request is an HTTP method that sends data to the server for further processing. Unlike a GET request, which retrieves data from the server, a POST request is used when the client wants to submit data to the server. This data can be in the form of input form, JSON objects, etc. depending on the specific requirements of the application.

When making a POST request, we include the data to be submitted in the body of the request. This data is typically sent in the form of key-value pairs in the form of JSON. The content type of the request header specifies the format of the data being sent. Common content types include “application/x-www-form-urlencoded” for form data and “application/json” for JSON data.

The server, upon receiving the POST request, processes the data. Once the server has processed the request, it sends an HTTP response back to the client, indicating the status of the operation.

Now let’s discuss one POST request as shown below




Here, through this request, we want to create a new placeholder resource on the server by providing all the required values in the request body.On the server side, the new resource will be created with all the provided information and a response will be sent back to the client. Look at the following screenshot


When we execute this script, we get the below response from server.



In the above request with all the data. The operation is successful and hence we get the response code as 201.


Here, In the above request, if you have noticed, we are creating a resource on the server, and values for that resource we are directly passing into the request body. What if we want to send multiple requests using the same test? Let’s see how we can do that.

How to prepare dynamic JSON request body

We need to parameterize the request body to make API calls dynamic and flexible. This enables us to send different data values for various scenarios without modifying the structure of the request.

Parameterization of the request body involves replacing specific values or placeholders in the body with dynamic data. This approach offers several benefits, including code reusability, maintainability, and the ability to customize API requests for different use cases.

Let’s create another class that contains the request body.



Now we will not use static values in the request body directly. Instead, we will pass these values dynamically.



Here in the body, I am calling addResource() method from RequestPayload class, and passing the values here which will replace the variables in the Request Body



Now, what if we want to run this test say 10 times, then whether we will change these values 10 times and run the script? The answer is NO. Let’s see how we can achieve this.

Data providers for Parameterizing the API Tests

We will use the DataProvider annotation from the TestNG.

In TestNG, the @DataProvider annotation is used to provide data for parameterized tests. It allows you to supply test data from various sources such as arrays, Excel files, databases, etc. The @DataProvider annotated method should return an array of objects, where each object represents a set of test data.

Let’s take an example:


In this example, the dataProviderMethod() is annotated with @DataProvider(name = “ResourceData”), which specifies the name of the data provider. It returns a 2D array of Object where each row represents a set of test data.

The addResources() method is annotated with @Test(dataProvider = “ResourceData”), indicating that it should use the data provided by the “ResourceData” data provider. The test method takes parameters that match the data provided by the data provider (in this case, a String and an int)

Here’s sample code

public class PostRequestDetails {

@org.testng.annotations.Test(dataProvider = "ResourceData")
public void addResources(String title, int id) {
ValidatableResponse response;
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
response = RestAssured.given().contentType("application/json")
.body(RequestPayload.addResource(title, id))
.when().post("/posts").then();
response.statusCode(201).log().all();
}


@DataProvider(name="ResourceData")
public Object[][] getData()
{
return new Object[][] {{"Story1",1},{"Story2",2},{"Story3",3},{"Story4",4}};
}
}

Here you have to make a proper connection by setting the exact data provider name to the Test method. And also the number of parameters that we are sending from DataProvider should exactly match with the parameters in the Test method.

Conclusion

In conclusion, this article has provided an in-depth exploration of POST API requests and their significance. We began by defining the POST method and highlighting its fundamental role in sending data to a server. We explored common data formats like JSON.


How Rest API Works?

REST (Representational State Transfer) API (Application Programming Interface) works as a set of rules and conventions for building and interacting with web services. Here's a step-by-step breakdown of how a REST API works:

  1. Resource Identification:

    • In REST, everything is considered a resource, such as data or services. Each resource is identified by a unique URI (Uniform Resource Identifier). For example, a URI might look like https://api.example.com/users.
  2. HTTP Methods (Verbs):

    • RESTful APIs use standard HTTP methods (GET, POST, PUT, DELETE, etc.) to perform operations on resources.
      • GET: Retrieve data from a resource.
      • POST: Create a new resource.
      • PUT/PATCH: Update an existing resource.
      • DELETE: Remove a resource.
  3. Request:

    • When a client (such as a web browser or mobile app) wants to interact with a resource, it sends an HTTP request to the server. The request includes the method, headers (for additional information), and, if needed, a request body with data (e.g., for creating or updating a resource).
  4. Server Processing:

    • The server, which hosts the API, processes the incoming request. It interprets the HTTP method and URI to determine the action to perform on the specified resource.
  5. Application Logic:

    • The server executes the application logic associated with the requested operation. This could involve querying a database, performing calculations, or interacting with other services.
  6. Response:

    • After processing the request, the server sends back an HTTP response to the client. The response includes a status code indicating the success or failure of the request, headers, and, if applicable, a response body with data.
  7. Status Codes:

    • HTTP status codes convey the result of the operation. Common codes include:
      • 200 OK: Successful GET request.
      • 201 Created: Successful POST request (resource created).
      • 204 No Content: Successful request with no response body.
      • 400 Bad Request: Client error.
      • 401 Unauthorized: Authentication failure.
      • 404 Not Found: Resource not found.
      • 500 Internal Server Error: Server error.
  8. Statelessness:

    • REST APIs are stateless, meaning each request from a client contains all the information needed for the server to fulfill that request. The server doesn't store any information about the client between requests.
  9. Hypermedia (HATEOAS):

    • REST APIs may include hypermedia links in responses, allowing clients to navigate the application by following links rather than relying on out-of-band information.
  10. Client-Side Processing:

    • The client processes the server's response, extracting and displaying relevant information. It may then make additional requests based on user interactions or application logic.

 -----------------------------------

What are the common API testing types?

•Functional Testing
•Load testing
•Runtime/ Error Detection
•Security testing
•Penetration testing
•Fuzz testing
•Interoperability testing

 What must be checked when performing API testing?

•During the API testing process, a request is raised to the API with the known data. This way you can analyze the validation response. While testing an API, you should consider:
•Accuracy of data
•Schema validation
•HTTP status codes
•Data type, validations, order and completeness
•Authorization checks
•Implementation of response timeout
•Error codes in case API returns, and
•Non functional testing like performance and security testing

 What are major challenges faced in API testing?

•Parameter Selection
•Parameter Combination
•Call sequencing
•Output verification and validation
•Another important challenge is providing input values, which is very difficult
as GUI is not available in this case.

What kinds of bugs that API testing would often find?

Ans: Functional Bugs: API testing verifies if the API behaves as expected and adheres to the defined functionality. It helps identify bugs related to incorrect data validation, improper handling of input parameters, incorrect response formats, missing or inconsistent data, and unexpected behavior.

Integration Bugs: API testing ensures the smooth integration of different software components or systems. It can identify bugs related to incorrect API versioning, incompatible data formats, improper data exchange etc.

Performance Bugs: It helps identify performance-related bugs such as slow response times, high resource utilization, memory leaks, poor caching mechanisms, and bottlenecks under heavy loads

Security Vulnerabilities: API testing uncovers security vulnerabilities that could expose sensitive data or allow unauthorized access.

Error Handling Bugs: API testing helps uncover bugs related to improper error handling, inconsistent error codes, misleading error messages, and vulnerabilities that could potentially expose sensitive information.

Missing or duplicate functionality
•Fails to handle error conditions gracefully
•Stress
•Reliability
•Security
•Unused flags
•Not implemented errors
•Inconsistent error handling
•Performance
•Multi threading issues
•Improper errors

What is API documentation?

•The API documentation is a complete, accurate technical writing giving
instructions on how to effectively use and integrate with an API.
•It is a compact reference manual that has all the information needed to work
with the API.

What are API documentation templates that are commonly used?

•Swagger
•Miredot
•Slate
•FlatDoc
•API blueprint
•RestDoc

Which information is exposed in the web developer tool?

Ans: Request Header, Request payload, Response body and cookies, Status codes, etc are exposed in the developer tool.


Perform RESTFUL WebServices Testing?

What are tools could be used for API testing?

A few of common tools are:
•Postman --
https://www.getpostman.com/downloads/
•SoapUi
•Tosca
•Apigee
•Katalon Studio etc.

RESTClient plugin for firefox browser

 CURL

cURL is a command-line tool for getting or sending files using URL syntax. Since cURL uses libcurl, it supports the same range of common Internet protocols that libcurl does.

Postman for testing API:

Postman is designed to check requests from the client to the server and receive a response from the back-end with a great user interface. The developers of this tool say “Postman is a powerful set of API testing tools that have become a must for many developers. We make great products to help you create stunning APIs and improve development productivity. Postman is used by more than a million developers around the world, and this number is constantly growing. We plan to develop other products to provide developers with the most powerful solution for developing and testing APIs." Postman provides a graphical user interface for generating and validating requests.

Postman-level automation allows you to perform the following test steps:

  • Saving Tests
  • Create test collections
  • Postman Standard Tests
  • Modify tests for yourself in the old and new version
  • Get data from object tree JSON, XML
  • Manage environment variables
  • Run one test several times
  • Download test data from file
  • Create a lot of data with unique values
How to install postman in chrome browser:
Postman is available as a native app (recommended) for Mac / Windows / Linux: 
 Go to Site:https://www.postman.com/downloads/ click on download button
After download double click on Postman icon then postman home page will show

It is also very easy and understandable to use the menu to select the type of request.

And what is very important, Postman has the ability to write a testing script. JavaScript is used for this. The presence of JavaScript allows many developers to easily join the testing process and write small, but effective test scripts. On the Postman documentation site, there are very clear and varied examples of writing test scripts, it is highly recommended that you look at them and automate the verification of the most common requests to test the API in your project.

What is Postman collection?

Ans: In Postman, the collection is a structured format used to organize and group API requests, along with their associated data, tests, and documentation. a collection can be thought of as a folder or container that holds multiple API requests. It provides a centralized place to store and organize all the endpoints related to a particular API or project.

What is Postman Collection Runner?

Ans: Runner is when a group of API requests is run in a collection for multiple Iterations with different sets of data

What is the difference between HTTP and HTTPS?

Ans: The main difference between HTTP and HTTPS lies in the level of security they provide when communicating over the internet:

  1. HTTP (Hypertext Transfer Protocol): HTTP is the protocol used for transmitting data between a web server and a web browser. It operates over the TCP/IP protocol and sends data as plain text. HTTP is not secure by default, meaning the data transferred between the client and the server is not encrypted. This lack of encryption makes it susceptible to eavesdropping, data tampering, and unauthorized access. It is commonly used for non-sensitive information transfer.
  2. HTTPS (Hypertext Transfer Protocol Secure): HTTPS is the secure version of HTTP. It uses a combination of HTTP and SSL/TLS (Secure Sockets Layer/Transport Layer Security) protocols to provide encrypted communication over the Internet. HTTPS ensures the confidentiality and integrity of data by encrypting it before transmission and decrypting it upon receipt. This encryption prevents unauthorized interception and protects against data tampering. HTTPS is commonly used for secure online transactions, sensitive data transfer (e.g., login credentials, financial information), and protecting user privacy.

12. What is Authentication and Authorization?

Ans: Authentication: Authentication is the process of verifying the identity of a user, system, or entity. It ensures that the claimed identity is valid and trustworthy before granting access to protected resources. Authentication methods involve the presentation of credentials, such as usernames, passwords, digital certificates, biometrics, or other factors that prove the identity of the entity requesting access.

Authorization, on the other hand, is the process of granting or denying access to specific resources or functionalities based on the authenticated identity and the assigned access rights. Once a user or system is authenticated, authorization determines the level of access or permissions they have within the system.

13. What are different Authentication methods available?

Ans: Commonly used Authentication methods are:

Basic Authentication: Basic Authentication is an HTTP-based authentication scheme. The client includes a Base64-encoded username and password in the Authorization header of the request. The server verifies the credentials against a user database or other authentication mechanisms. However, Basic Authentication has the limitation of sending credentials in plain text, making it vulnerable to interception.

Bearer Token: Bearer token authentication involves the use of a token issued by an authentication server. The client includes the token in the Authorization header of the API request, typically as a bearer token prefixed with the word “Bearer.” The server validates the token to authenticate the client. Bearer tokens are commonly used in OAuth 2.0 and JWT (JSON Web Token) authentication

OAuth 2.0: OAuth 2.0 is an industry-standard authorization framework that allows third-party applications to access resources on behalf of a user. It involves the exchange of tokens between the client, the authorization server, and the resource server. OAuth 2.0 provides a secure and standardized way of delegating access and is commonly used for API authentication and authorization in scenarios like social login or granting API access to external applications.

14. What do you mean by an idempotent API request?

Ans: An idempotent API request is a request that can be repeated multiple times without producing different results. In other words, making the same request multiple times should have the same effect as making it only once.

Idempotent requests are commonly associated with HTTP methods, especially the GET, PUT, and DELETE methods:

  • GET: The GET method is inherently idempotent. Retrieving the same resource multiple times should yield the same response, and it should not modify any data on the server.
  • PUT: The PUT method is idempotent when used to update or replace a resource. Sending the same PUT request multiple times with the same payload should result in the same resource state.
  • DELETE: The DELETE method is also idempotent. Deleting a resource multiple times should have the same effect, and subsequent DELETE requests should not produce any errors.

Authorizing requests

APIs use authorization to ensure that client requests access data securely. This can involve authenticating the sender of a request and verifying that they have permission to access or manipulate the relevant data. If you're building an API, you can choose from a variety of auth models. If you're integrating a third-party API, the required authorization will be specified by the API provider.

You can pass auth details along with any request you send in Postman. Auth data can be included in the header, body, or as parameters to a request. If you enter your auth details in the Authorization tab, Postman will automatically populate the relevant parts of the request for your chosen auth type. You can use variables and collections to define authorization details more safely and efficiently, letting you reuse the same information in multiple places.

Contents

What are the types of authentication?
  • Single-Factor/Primary Authentication. ...
  • Two-Factor Authentication (2FA) ...
  • Single Sign-On (SSO) ...
  • Multi-Factor Authentication (MFA) ...
  • Password Authentication Protocol (PAP) ...
  • Challenge Handshake Authentication Protocol (CHAP) ...
  • Extensible Authentication Protocol (EAP)

Specifying authorization details

With a request open in Postman, use the Authorization tab Type dropdown to select an auth type. Postman will prompt you to complete the relevant details for your selected type. The correct data values will be determined by your API at the server side—if you're using a third party API you will need to refer to the provider for any required auth details.

Auth Types

You can use these auth types with Newman and monitors as well as in the Postman app.

When you select a type, Postman will indicate which parts of the request your details will be included in, for example the header, body, URL, or query parameters. Postman will add your auth details to the relevant parts of the request as soon as you select or enter them, so you can see how your data will be sent before attempting to run the request.

Auth Setup in Request

Your auth data will appear in the relevant parts of the request, for example in the Headers tab. To show headers added automatically, click the hidden button.

Questions QUIZ

Which HTTP status code is commonly returned when a bearer token is invalid or expired?The author can see how you vote. Learn more

Which HTTP status code is commonly returned when a bearer token is invalid or expired?

a) 200 OK


b) 401 Unauthorised


c) 403 Forbidden


d) 500 Internal Server Error

--------------------------------------------------------------------------------------------------------

can you give me some limitations in postman for api testing?

Here are some of the limitations of Postman for API testing:

  1. Collaboration: While Postman does have some collaboration features, it's not as robust as some other solutions specifically designed for collaboration, such as collaborative API design tools.

  2. Load Testing: Postman has limited load testing capabilities and is not as feature-rich as dedicated load testing tools.

  3. Complex Workflows: Postman can become complex to use for complex workflows and integrations, as it may require multiple scripts and manual testing to validate results.

  4. Limited Integrations: While Postman can integrate with a number of popular tools and services, it is limited in comparison to other API testing solutions that offer a wider range of integrations.

  5. Speed: Postman can be slow to execute tests, especially when dealing with large amounts of data, which can become an issue for large-scale API testing.

  6. Cost: While Postman is free for individual use, the cost of using the Postman Pro and Postman Enterprise editions can add up for large teams, especially for organizations that need additional features and integrations.


Reference Link:

https://learning.postman.com/docs/sending-requests/authorization/

API DOC:

2)https://documenter.getpostman.com/view/4012288/TzK2bEa8#e388e723-b3e6-4a9b-99d5-609cbd6d4a4d

Authorization key:

https://app.getpostman.com/dashboard/integrations/pm_pro_api/list

What is JSON?

JSON stands for JavaScript Object Notation
JSON is a lightweight format for storing and transporting data
JSON is often used when data is sent from a server to a web page
JSON is "self-describing" and easy to understand

JSON Example

This example defines an employees object: an array of 3 employee records (objects):
{
"employees":[
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]

JSON Syntax Rules

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs, just like JavaScript object properties.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

"firstName":"John"
JSON names require double quotes. JavaScript names do not.

JSON Objects

JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John""lastName":"Doe"}

JSON Arrays

JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:

"employees":[
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects

HTTP Status code:

·         1×× Informational



·         2×× Success



·         3×× Redirection



·         4×× Client Error



·         5×× Server Error


================================================================
what is the difference between queryparameters and path parameters in RESTAPI?

Query parameters are used to filter and sort the data that is returned from an API endpoint, or to specify additional options for the request. They are added to the API endpoint as key-value pairs, and are separated from the main API endpoint URL by a ? symbol. For example, in the following API endpoint:

https://api.example.com/resources?sort=asc&limit=10

The sort and limit parameters are query parameters. They are used to specify that the data should be sorted in ascending order and that only 10 results should be returned.

Path parameters, on the other hand, are used to specify a specific resource or resources that should be returned or modified. They are included in the API endpoint as part of the URL path, and are typically used to identify a specific resource or resources within a collection of resources. For example, in the following API endpoint:

https://api.example.com/resources/12345

The 12345 is a path parameter that is used to specify a specific resource with the ID 12345 from the resources collection.

In summary, query parameters are used to filter and sort data and to specify additional options for a request, while path parameters are used to identify specific resources within a collection.

===========================

How can you give headers in RestAssuredFramework?
RestAssured.given()
                        .header("accept","application/json")

What is Rest Assured?

Rest Assured is a Java library that helps us test APIs, specifically REST APIs. It behaves like a headless client to access REST web services. Rest Assured supports Behaviour Data Driver programming which can be integrated with TestNG framework and JUnit.

Advantages of rest assured :

  1. REST is open source.
  2. It authenticates and justifies the response to requests like get, post, patch, and delete.
  3. It provides a Given/When/Then test annotation, which makes tests simple enough to understand.
  4. It supports CI/CD integration.
  5. It can be used with any customized or open-source reporting tool.
  6. It can be easily integrated with JUnit and TestNG frameworks.

The disadvantage of rest assured :

  1. It requires prerequisite knowledge of the Java programming language.
  2. It does not support SOAP APIs explicitly.
  3. It has an inbuilt reporting feature.
  4. REST Assured is not purely thread-safe.

How RestAssured works?

Rest assured mainly works in 3 phases in which

  1. We create an HTTP request which can either be GET, PUT, PATCH, or DELETE.
  2. Then we send these requests to the server and then the server processes the data and sends back the response.
  3. After receiving the response we validate all the parameters present in the response.

RestAssured Features:

REST-assured offers a bunch of nice features like a DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads

Some Functions that are used to fetch parameters of response :

1. getStatusCode(): To retrieve the status code from the response.

2. getStatusLine(): To retrieve the status line from the response.

3. body().asString(): To retrieve the body in the form of a string.

4. getHeader(“String”): To retrieve the header from the response.

5. jsonPath().getString(“Key”): To retrieve the value of a desired key from the response.

6. For validating time from the response:
ValidatableResponse valRes = response.then();
valRes.time(Matchers.lessThanOrEqualTo(time_in_long));

7. For validating the JSON schema of the response:
ValidatableResponse valRes = response.then();
valRes.body(JsonSchemaValidator.matchesJsonSchema(new File(json_schema_file_path)));

8. getContentType(): To retrieve the content type header.

9. getCookies(): To retrieve the cookies from the response.

10. getCookie(“Key”): To retrieve the specific cookie from the response.

11. getTime(): To retrieve the exact time taken by the request to process.

To implement tests, first, we need to fetch the required attribute from the response and then using Assertions we will compare the actual and expected attributes.

Some assertion functions that can be used in the tests:

1. assertEquals(actual_result, expected_result, “Message to be displayed if the test fails”)

2. assertNotEquals(actual_result, expected_result, “Message to be displayed if the test fails”)

3. assertTrue(boolean condition)

4. assertFalse(boolean condition)

5. assertNotNull(String)

REST Assured-Setting up environment using Maven

To start building code for our REST API automation testing, we will setup our environment using two different ways, using rest assured with Maven dependencies and by configuring external jar files for REST-Assured.
how to setup Rest Assured using Maven :
I am using Eclipse Neon here, you can use any version you are comfortable with. Please make sure you have an internet connection before creating a maven project, the dependencies will get automatically downloaded from maven central repository over the internet.
Open Eclipse and Click on File – New – Project.
Select Maven – Maven Project as below :
Click next. Following window will appear :
Click on Create a simple project(skip archetype selection)

Click Next. Following window will appear :

Fill the required information as above.
Click Finish. Your project will be created as below :




Make sure pom.xml is created. We need to add maven dependenices in pom.xml file.
Maven Dependencies
You just need to copy the code from this below snippet and paste it inside your pom.xml file. This code will download all the jars we need to perform REST API testing using REST-Assured, you do not need to worry about searching correct jars, all will be taken care by Maven, please notice Maven Dependencies folder have many jars in it now, those jars are downloaded by Maven in your workspace.

1)https://mvnrepository.com/artifact/io.rest-assured/rest-assured


2)TestNG : https://mvnrepository.com/artifact/org.testng/testng

3)Hamcrest: https://mvnrepository.com/artifact/org.hamcrest/hamcrest

4)JSON: https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

5)JSON Schema Validator: https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator



----------------------------

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>RestAssuredAPIAutomationMay62022</groupId>
  <artifactId>RestAssuredAPIAutomationMay62022</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<testng.version>7.7.1</testng.version>
<rest-assured.version>5.3.0</rest-assured.version>
<hamcrest-all.version>1.3</hamcrest-all.version>
<json-simple.version>1.1.1</json-simple.version>
<lombok.version>1.18.24</lombok.version>
<jackson-databind.version>2.14.1</jackson-databind.version>
<org-json.verion>20220924</org-json.verion>
<java-faker.version>1.0.2</java-faker.version>
<log4jcore.version>2.19.0</log4jcore.version>
<log4japi.version>2.19.0</log4japi.version>
<json-schema-validator.version>5.3.0</json-schema-validator.version>
<allure.version>2.20.1</allure.version>
<awaitility.version>4.2.0</awaitility.version>
<aspectj.version>1.9.19</aspectj.version>
<maven-compiler-plugin.version>3.10.1</maven-compiler-plugin.version>
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
<java-release.version>11</java-release.version>
<suite-xml>test-suite/testng.xml</suite-xml>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${json-schema-validator.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${hamcrest-all.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json-simple.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${org-json.verion}</version>
</dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>${java-faker.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4jcore.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4japi.version}</version>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>${allure.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.awaitility/awaitility -->
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${java-release.version}</release>
<encoding>UTF-8</encoding>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${suite-xml}</suiteXmlFile>
</suiteXmlFiles>
<argLine>-Dfile.encoding=UTF-8 -Xdebug -Xnoagent</argLine>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>3.0</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>2.12.0</version>
<configuration>
<reportDirectory>${project.build.directory}/target/allure-report</reportDirectory>
<reportVersion>${allure.version}</reportVersion>
<allureDownloadUrl>
https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/${allure.version}/allure-commandline-${allure.version}.zip
</allureDownloadUrl>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
  
</project>


Your pom.xml file will look like below after pasting the above code in the file. Once you hit Save button, Maven will start downloading all the dependencies of rest-assured.




Congratulations you successfully created your Maven project.


<<<BUILD SECTION IN THE POM.XML>>>
 
  <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
<plugins>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>

</plugins>

</build>


Reference Links:

1)Rest-assuredProjectWebSite
2)Rest-assuredDocumentation
3)MoreExampleOn-restful-web-services


pom.xml file:
---------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>APIRestAssuredInBDDStyle-Apr192023</groupId>
  <artifactId>APIRestAssuredInBDDStyle-Apr192023</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
  
  <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    </plugin>
  </plugins>

 </build> 
  <dependencies>
  
  <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-path</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/xml-path -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>xml-path</artifactId>
    <version>5.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>java-hamcrest</artifactId>
    <version>2.0.0.0</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220924</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.11.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>7.11.1</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-core -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-core</artifactId>
    <version>7.11.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.masterthought/cucumber-reporting -->
<dependency>
    <groupId>net.masterthought</groupId>
    <artifactId>cucumber-reporting</artifactId>
    <version>5.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.2</version>
</dependency>
  
  
  </dependencies>
  
</project>

===============================================================
Package:base
package com.qa.api.rest.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class TestBase {
/**
* This Method returns given propery value
* Accessmodifier static datatype methodname(datatype key){logic; return value;}
* @throws IOException 
*/

public static String readPropertyValue(String key) throws IOException {
//Step1-create object for Properties class
Properties prop=new Properties();
//Step2:Read the properties file using FileInputStream class
File f=new File(System.getProperty("user.dir")+"\\src\\test\\java\\com\\qa\\api\\rest\\config\\config.properties");
try {
FileInputStream fis=new FileInputStream(f);
//step3 - load all the properties
prop.load(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return prop.getProperty(key);
}
}
==============================================================
package: config
filename:config.properties

baseUrl=https://reqres.in/
getAllUserEndPoint=api/users
getSingleUserEndPoint=api/users
getSingleUserNotFoundEndPoint=api/users/23
======================================================

Feature Files:
Folder name:Features
ReqResGETApi.feature

Feature: REQRES GET API Feature

  Scenario: ReqRes GET API to list all users
    Given provide valid endpoint to fetch all users
    When the request is send to the server
    Then validate the response statuscode 200

  Scenario Outline: Reqres GET API to list all users with scenario outline
    Given provide valid endpoint to fetch all users
    When the request is send to the server with page number as "<page>"
    Then validate the response of first user record having email as "<emailId>"
    And validate response statuscode <respStatusCode>

    Examples: 
      | page | emailId                  | respStatusCode |
      |    2 | michael.lawson@reqres.in |            200 |
      |    1 | george.bluth@reqres.in   |            200 |

  @smoke @regression
  Scenario: ReqRes GET Single user
    Given provide valid endpoint to fetch the single user
    When the request is send to the server to fetch single user
    Then validate the response statuscode 200
    And validate the response body fields
    |2|janet.weaver@reqres.in|Janet|Weaver|

  Scenario: ReRes GET SingleUser Not Found
    Given provide valid endpoint to fetch the single userNotFound
    When the request is send to the server to fetch single user not found
    Then validate the response statuscode
          | 404 |

     ========================================================================
ReqResPOSTApi.feature
Feature: REQRES POST API Feature

  Scenario: ReqRes POST API to create user
    Given provide valid endpoint to create user
    When the request is send to the server with requestbody
    Then validate create user response statuscode
      | 201 |
    And validate the responsebody fields

  Scenario Outline: ReqRes POST API to create users
    Given provide valid endpoint to create users
    When the request is send to the server with requestbody as "<name>" and "<job>"
    Then validate create user response statuscode
      | 201 |
    And validate the responsebody fields

    Examples: 
      | name      | job                  |
      | Morpheus  | leader               |
      | Ramesh Ch | Automation Test lead |
=========================================================================
ReqResPUTApi.feature
@putapi
Feature: REQRES PUT API Feature
  Scenario: ReqRes PUT API to update user
    Given provide valid endpoint to update user
    When the request is send to the server with requestbody to update
    Then validate update user response statuscode
      | 200 |
    And validate the update responsebody fields
=========================================================================
ReqResDeleteApi.feature

@deleteapi
Feature: REQRES DELETE API Feature
  Scenario: ReqRes DELETE API to delete the specific user
    Given provide valid endpoint to delete the user
    When the request is send to the server delete the user
    Then validate delete user response statuscode
      | 204 |
========================================================================
StepDefinition files
package name:step_def
======================
GetAPITest.java
--------------------
package step_def;

import java.util.List;

import org.junit.jupiter.api.Assertions;
import com.qa.api.rest.base.TestBase;

import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;

public class GetAPITest extends TestBase{

Response resp;
@Given("^provide valid endpoint to fetch all users$")
public void provide_valid_endpoint_to_fetch_all_users() throws Throwable {
   //setting the base Url
RestAssured.baseURI=readPropertyValue("baseUrl");
   //setting the endpoint url
RestAssured.basePath=readPropertyValue("getAllUserEndPoint");
}

@When("^the request is send to the server$")
public void the_request_is_send_to_the_server() throws Throwable {
   resp=RestAssured.given().header("Accept","application/json").
   header("Content-type", "application/json").
   queryParam("page", 2).
   when().
   get().
   then().
   contentType("application/json").
   extract().response();
}

@Then("^validate the response statuscode 200$")
public void validate_the_response_statuscode_200() throws Throwable {
   int respCode=resp.getStatusCode();
   Assertions.assertEquals(respCode, 200);
}

@When("^the request is send to the server with page number as \"([^\"]*)\"$")
public void the_request_is_send_to_the_server_with_page_number_as_something(int pageNumber) throws Throwable {
resp=RestAssured.given().header("Accept","application/json").
   header("Content-type", "application/json").
   queryParam("page", pageNumber).
   when().
   get().
   then().
   contentType("application/json").
   extract().response();
}

@Then("^validate the response of first user record having email as \"([^\"]*)\"$")
public void validate_the_response_of_first_user_record_having_email_as_something(String emailid) throws Throwable {
   //extracting the response body field value
String email=resp.path("data[0].email");
Assertions.assertEquals(email, emailid);
}

@Then("^validate response statuscode (.+)$")
public void validate_response_statuscode(int respstatuscode) throws Throwable {
int respCode=resp.getStatusCode();
Assertions.assertEquals(respCode, respstatuscode); 
}

@Given("^provide valid endpoint to fetch the single user$")
public void provide_valid_endpoint_to_fetch_the_single_user() throws Throwable {
   //set the base url
RestAssured.baseURI=readPropertyValue("baseUrl");
//set the basepath
RestAssured.basePath=readPropertyValue("getSingleUserEndPoint");
}

@When("^the request is send to the server to fetch single user$")
public void the_request_is_send_to_the_server_to_fetch_single_user() throws Throwable {
  resp=RestAssured.given().header("Accept","application/json").
   header("Content-type", "application/json").
   when().
   get("/2").
   then().
   contentType("application/json").
   extract().response();
}

@Then("^validate the response body fields$")
public void validate_the_response_body_fields(DataTable values) throws Throwable {
   List<List<String>>ls=values.asLists();
int id=resp.path("data.id");
   System.out.println("id value is:"+id);
   Assertions.assertEquals(Integer.parseInt(ls.get(0).get(0)), id);
   //fetch the email
   String emailVal=resp.path("data.email");
   System.out.println("email value is:"+emailVal);
   Assertions.assertEquals(ls.get(0).get(1), emailVal);
 //fetch the first name
   String firstNameVal=resp.path("data.first_name");
   System.out.println("firstName value is:"+firstNameVal);
   Assertions.assertEquals(ls.get(0).get(2), firstNameVal);
   
 //fetch the lastname
   String lastnameVal=resp.path("data.last_name");
   System.out.println("lastname value is:"+lastnameVal);
   Assertions.assertEquals(ls.get(0).get(3), lastnameVal);
}

@Given("^provide valid endpoint to fetch the single userNotFound$")
public void provide_valid_endpoint_to_fetch_the_single_usernotfound() throws Throwable {
//set the base url
RestAssured.baseURI=readPropertyValue("baseUrl");
//set the basepath
RestAssured.basePath=readPropertyValue("getSingleUserNotFoundEndPoint");
}

@When("^the request is send to the server to fetch single user not found$")
public void the_request_is_send_to_the_server_to_fetch_single_user_not_found() throws Throwable {
resp=RestAssured.given().header("Accept","application/json").
   header("Content-type", "application/json").
   when().
   get().
   then().
   contentType("application/json").
   extract().response();  
}

@Then("^validate the response statuscode$")
public void validate_the_response_statuscode(DataTable exrespcode) throws Throwable {
  int respCode=resp.getStatusCode();
 List<String>ls=exrespcode.asList();
 int expval=Integer.parseInt(ls.get(0));
Assertions.assertEquals(respCode,expval); 
}

}


====================================================================
package step_def;
import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;

import com.qa.api.rest.base.TestBase;

import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;

public class PostAPITest extends TestBase{

Response resp;
JSONObject jsonObj=new JSONObject();
@Given("^provide valid endpoint to create user$")
public void provide_valid_endpoint_to_create_user() throws Throwable {
    //set the baseUrl
RestAssured.baseURI=readPropertyValue("baseUrl");
//set the base path
RestAssured.basePath=readPropertyValue("getAllUserEndPoint");
}

@When("^the request is send to the server with requestbody$")
public void the_request_is_send_to_the_server_with_requestbody() throws Throwable {
jsonObj.put("name", "CH Ramesh");
jsonObj.put("job", "AutomationTestLead"); 
resp=RestAssured.given().header("Accept", "application/json").
    header("Content-Type","application/json").
    body(jsonObj.toString()).
    when().
    post().
    then().
    extract().response();
     
     
}

@Then("^validate create user response statuscode$")
public void validate_create_user_response_statuscode(DataTable code) throws Throwable {
   int respCode=resp.getStatusCode();
  System.out.println("session id is:"+resp.getSessionId());
  System.out.println("statusline:"+resp.getStatusLine());
  System.out.println("response time:"+resp.getTime());
   Assertions.assertEquals(Integer.parseInt(code.asList().get(0)), respCode);
}

@Then("^validate the responsebody fields$")
public void validate_the_responsebody_fields() throws Throwable {
    String nameval=resp.path("name");
    System.out.println("name value is:"+nameval);
    Assertions.assertEquals(jsonObj.get("name"), nameval);
    String jobval=resp.path("job");
    Assertions.assertEquals(jsonObj.get("job"), jobval);
}
@Given("^provide valid endpoint to create users$")
public void provide_valid_endpoint_to_create_users() throws Throwable {
    //set base Url
RestAssured.baseURI=readPropertyValue("baseUrl");
//set the base path
RestAssured.basePath=readPropertyValue("getAllUserEndPoint");
}
@When("^the request is send to the server with requestbody as \"([^\"]*)\" and \"([^\"]*)\"$")
public void the_request_is_send_to_the_server_with_requestbody_as(String name, String job) throws Throwable {
jsonObj.put("name", name);
jsonObj.put("job", job); 
resp=RestAssured.given().header("Accept", "application/json").
    header("Content-Type","application/json").
    body(jsonObj.toString()).
    when().
    post().
    then().
    extract().response();

}




}
====================================================================
package step_def;

import java.util.List;

import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;

import com.qa.api.rest.base.TestBase;

import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;

public class PutApiTest extends TestBase{

Response resp;
JSONObject jsonObj=new JSONObject();

@Given("^provide valid endpoint to update user$")
public void provide_valid_endpoint_to_update_user() throws Throwable {
//set the baseUrl
RestAssured.baseURI=readPropertyValue("baseUrl");
//set the base path
RestAssured.basePath=readPropertyValue("getAllUserEndPoint");
}

@When("^the request is send to the server with requestbody to update$")
public void the_request_is_send_to_the_server_with_requestbody_to_update() throws Throwable {
jsonObj.put("name", "Muniraja");
jsonObj.put("job", "Automation Architect"); 
resp=RestAssured.given().header("Accept", "application/json").
    header("Content-Type","application/json").
    body(jsonObj.toString()).
    when().
    put("/2").
    then().
    extract().response();
}

@Then("^validate update user response statuscode$")
public void validate_update_user_response_statuscode(DataTable table) throws Throwable {
  int respCode=resp.getStatusCode();
  System.out.println("Update Api Status code is:"+respCode);
  //implement DataTable concept
  List<String>ls=table.asList();
  //convert String object into int
  int expRespCode=Integer.parseInt(ls.get(0));
  Assertions.assertEquals(expRespCode, respCode);
}

@Then("^validate the update responsebody fields$")
public void validate_the_update_responsebody_fields() throws Throwable {
    String respname=resp.path("name");
    System.out.println("resp name is:"+respname);
    Assertions.assertEquals(jsonObj.get("name"), respname);
    String respjob=resp.path("job");
    System.out.println("resp job is:"+respjob);
    Assertions.assertEquals(jsonObj.get("job"), respjob);
    String respupdateAt=resp.path("updatedAt");
    System.out.println("updated at:"+respupdateAt);
    
}
}
========================================================================
package step_def;

import java.util.List;

import org.junit.jupiter.api.Assertions;

import com.qa.api.rest.base.TestBase;

import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;

public class DeleteApiTest extends TestBase{
Response resp;
@Given("^provide valid endpoint to delete the user$")
public void provide_valid_endpoint_to_delete_the_user() throws Throwable {
    //set base url
RestAssured.baseURI=readPropertyValue("baseUrl");
//set basepath
RestAssured.basePath=readPropertyValue("getSingleUserEndPoint");
}

@When("^the request is send to the server delete the user$")
public void the_request_is_send_to_the_server_delete_the_user() throws Throwable {
   resp=RestAssured.given().header("Accept", "application/json").
    header("Content-Type","application/json").
    when().
    delete("/2").then().extract().response();
}

@Then("^validate delete user response statuscode$")
public void validate_delete_user_response_statuscode(DataTable table) throws Throwable {
  int respCode=resp.getStatusCode();
  System.out.println("Update Api Status code is:"+respCode);
  //implement DataTable concept
  List<String>ls=table.asList();
  //convert String object into int
  int expRespCode=Integer.parseInt(ls.get(0));
  Assertions.assertEquals(expRespCode, respCode);
}

}
=========================================================================
package:testRunner
 package testRunner;

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)

@CucumberOptions(
    features = "D:\\eclipseworkspaceAug2018\\RestAssuredAPIAutomationMay62022\\src\\test\\java\\Features",
    glue = {"step_def"},
    plugin={"pretty","html:target/report.html", "json:json_output/cucumber.json", "junit:junit_xml/cucumber.xml"},
    dryRun=false, //mapping between feature & stepdefinition is proper or not
    monochrome=true,//display the console output in a proper readable format
    publish = true,
    stepNotifications=true
    //tags = "@smoke"
    )
public class TestRunner {
   
}
========================================================

Structural Validation of JSON Using Rest Assured.

Introduction

Rest Assured is an open-source Java-based library used to test RESTful APIs. Using Rest Assured, we can test XML and JSON-based web services. It behaves like a headless client to access APIs and interact with them. It supports different HTTP methods like GETPOSTPUT and DELETE. It can be integrated with popular testing frameworks like Junit, TestNG, etc.

Rest Assured can be integrated with BDD frameworks like Cucumber and we can write BDD style code. Rest Assured supports the Gherkin syntax (Given/When/Then) making the tests human-readable and easy to understand. Rest Assured is implemented in a language called "Groovy."

Schema/Structure Validation

Upon receiving a valid HTTP request in the form of URL/URI from the client-side, the server returns a JSON response. Validating the response received from the server is a vital task in API Testing. While we talk about testing the response body, we can break the testing into 3 areas:

  • Structural/Schema Validation
  • Response Body Validation
  • Individual Element Validation

In this article, we will see how to perform Structural or Schema Validation of a JSON response. 

Let us consider that this is our Response JSON:

JSON
1
{
2
  "id": 10,
3
  "firstName": "Remi",
4
  "lastName": "Jullian",
5
  "email": "remi.jullian@abc.com",
6
  "programme": "Financial Analysis",
7
  "courses": [
8
    "Accounting",
9
    "Statistics"
10
  ]
11
}


For Schema validation, we need to create a schema for our JSON. This will act as our expected schema for validation. We can manually create the schema or we can use any online JSON schema generators to create our expected schema. 

Schema is nothing but a JSON file. It will have only datatype information and the expected keys of the JSON. There won't be any values present in the schema. 

The expected schema for the above JSON is seen below:

JSON

1
{
2
  "$schema": "http://json-schema.org/draft-04/schema#",
3
  "type": "object",
4
  "properties": {
5
    "id": {
6
      "type": "integer"
7
    },
8
    "firstName": {
9
      "type": "string"
10
    },
11
    "lastName": {
12
      "type": "string"
13
    },
14
    "email": {
15
      "type": "string"
16
    },
17
    "programme": {
18
      "type": "string"
19
    },
20
    "courses": {
21
      "type": "array",
22
      "items": [
23
        {
24
          "type": "string"
25
        },
26
        {
27
          "type": "string"
28
        }
29
      ]
30
    }
31
  },
32
  "required": [
33
    "id",
34
    "firstName",
35
    "lastName",
36
    "email",
37
    "programme",
38
    "courses"
39
  ]
40
}

Rest Assured Logic To Test the Schema

Step 1: Add a "JSON schema validator" dependency in pom.xml.

XML
1
        <dependency>
2
            <groupId>io.rest-assured</groupId>
3
            <artifactId>json-schema-validator</artifactId>
4
            <version>3.0.0</version>
5
        </dependency>


Step 2: Add a "hamcrest-all" dependency for asserting the JSON schema.

XML
1
        <dependency>
2
            <groupId>org.hamcrest</groupId>
3
            <artifactId>hamcrest-all</artifactId>
4
            <version>1.3</version>
5
            <scope>test</scope>
6
        </dependency>



Step 3: Load the expected "schema.JSON" in a file object.

Java
1
File schema = new File(System.getProperty("user.dir")+"schema.json");

Step 4: Fire the rest assured request, validate the response body using the matchesJsonSchema method. 

Java

1
given().get("http://localhost:8080/student/10").then().body(matchesJsonSchema(schema));



The matchesJsonSchema method validates the response body matches the structure—data type and the required keys. If there is any mismatch, it will report in the console. 

Full Code

Java

1
import static io.restassured.RestAssured.*;
2
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
3
import java.io.File;
4
import org.testng.annotations.Test;
5
6
public class StructureValidation {
7
    
8
    @Test
9
    public void JSONSchemaValidation() {    
10
        File schema = new File(System.getProperty("user.dir")+"schema1.json");
11
      given().
12
          get("http://localhost:8080/student/10").
13
      then().
14
          body(matchesJsonSchema(schema));      
15
    }



Step 5: Schema validation programmatically is very useful when you have a nested JSON, which is very time consuming if we need to validate manually.  

How to fetch test data from json file using jsonobject

1. Create a testdata.json file


2. Create a method which will fetch value from json object using key


public static String getTestData(String input) throws IOException, ParseException {
        String testdata;
        return testdata = (String) getJsonData().get(input);//input is the key
       
    }
   

3. Create a method as  getJsonData() with return type as JsonObject


public static JSONObject getJsonData() throws IOException, ParseException  {
       
        //pass the path of the testdata.json file
        File filename = new File("TestData//testdata.json");
        //convert json file into string
        String json = FileUtils.readFileToString(filename, "UTF-8");
        //parse the string into object
        Object obj = new JSONParser().parse(json);
        //give jsonobject o that I can return it to the function everytime it get called
        JSONObject jsonObject = (JSONObject) obj;
        return jsonObject;

    }

How to fetch test data from json file using jsonPath?

    Note: Use https://jsonpath.com/ to write your own jsonpath

    1. Create a testdata.json file


    2. Create a method which will fetch value from json object using key


public static String getdatafromjson(String path) throws IOException {
       
        File f = new File("TestData//testdata.json");
        String json = FileUtils.readFileToString(f, "UTF-8");
        String result;
        return result = JsonPath.read(json, path);
       
    }

There is one more way to do the same which is by using the POJO class, check the post below for all the steps in json to pojo conversion:

In the below pojo structure name is a string, jobs are a list of string, and cityModels is a map list. So for cityModels we need to create a separate POJO class as we have done below.

POJO Structure:

{

"name": "morpheus", "jobs": ["tester","developer","support"] "cityModels":[ { "Name":"bangalore", "Temperature":"30" }, { "Name":"delhi", "Temperature":"40" } ] }

POJO CLASS:


package pojo;


import java.util.List;


public class pojoTry {

private String name; // this is for the name filed in pojo

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

private List<String> jobs; // this is for jobs filed in pojo

public List<String> getJobs() {

return jobs;

}

public void setJobs(List<String> jobs) {

this.jobs = jobs;

}

private List<cityModel> citymodels; //refer the city model class below, we have created separate pojo class for it as it is a list of map

public List<cityModel> getCitymodels() {

return citymodels;

}

public void setCitymodels(List<cityModel> citymodels) {

this.citymodels = citymodels;

}


}


CityModel class:

package pojo;


public class cityModel {

private String name;

public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getTemperature() {

return temperature;

}


public void setTemperature(String temperature) {

this.temperature = temperature;

}


private String temperature;


}

==========================================================================================

Top 10 API Testing Interview Questions SET-1 for Automation Testers/QA/SDET?

1. What are the types of methods most used in RestAPI Testing?

GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS

P1 : GET POST DELETE
P2 : PUT
P3 : PATCH

2. What are the types of Status codes?
1xx informational response – the request was received, continuing process
2xx successful – the request was successfully received, understood, and accepted
3xx redirection – further action needs to be taken in order to complete the request
4xx client error – the request contains bad syntax or cannot be fulfilled
5xx server error – the server failed to fulfil an apparently valid request
3. What are the status codes you have come across in your API testing project?

200:  OK

201:  Created

204:  No Content

400:  Bad Request

401: Unauthorized

403: Forbidden

404: Not Found

302: Redirect

405: Method Not Allowed

422: Unprocessable Entity

417: Expectation failed

500: Internal Server Error
4. What is GET Method?

GET    Retrieve information about the REST API resource

5. What is POST Method?

POST    Create a REST API resource

6.What is PUT Method?

PUT    Update a REST API resource

7. What is DELETE Method?

DELETE    Delete a REST API resource or related component

8. What is HEAD method?

The HEAD method asks for a response identical to that of a GET request, but without the response body.
This is useful for retrieving meta-information written in response headers, without having to transport the entire content

9. What is OPTIONS method?

The OPTIONS method returns the HTTP methods that the server supports for the specified URL.
This can be used to check the functionality of a web server by requesting '*' instead of a specific resource.

What is the difference between PUT and POST method? REST API interview questions? Most asked RestAPI Automation Interview questions?

Ans)
PUT vs POST : An Example

Let’s list down when to use POST and when to use PUT :

GET     /user-management/users: Get all users
POST     /user-management/users: Create a new user

GET     /user-management/users/{id} : Get the user information identified by "id"
PUT     /user-management/users/{id} : Update the user information identified by "id"


It is good practice to use:

 - PUT for UPDATE operations.
 - POST for CREATE operations.

  • PUT is Idempotent 
  • POST is not Idempotent.

How to Validate REST API Request, Response Using Rest Assured




In the world of software development, it’s essential to ensure that our applications behave as expected. One critical aspect of this is validating HTTP status codes returned by our REST APIs. This article will explore how to use Rest Assured, a popular Java-based testing framework, to validate HTTP status codes.

How to Validate HTTP REST API Response

When a client sends a RESTful request to the server, in return the server sends the response back to the client with the requested resource.

Rest Assured provides a simple and effective way to validate HTTP status codes.

The server response contains following

  1. Status Code
  2. Error Message(If any)
  3. Response body
  4. Headers

In the previous article, we have seen our first REST API test, and now we will learn about its response and other validations.

Validating HTTP status codes is one of the most critical aspects of testing REST APIs. HTTP status codes indicate the outcome of a request, such as success or failure. Rest Assured provides a simple way to validate HTTP status codes using the statusCode() method.

When we talk about validation, one thing comes into our mind: we would have a mechanism, through which we read the entire response object and then validate the status code, response body, and other components.

The server sends the API request response in JSON or XML form. This depends on the Media-Type we pass in the API request call.

Also, the response from the server contains Headers, which are called response headers. We will get to know the format of the response from the Content-Type header of the response.

Let’s take an example of the same API which we discussed in our previous article.




When we hit this request, we receive the below response.





As we see in the above screenshot, the response has a status, headers, and body. It has a content-type attribute that has the value, on validating this header, the client knows what would be the response format.

Let us now proceed with validating the status part of the response.

Validating the Status Code

HTTP status codes are three-digit codes sent by a server to indicate the status of a requested resource. These codes are grouped into five classes, each with a specific meaning ranging from 1xx- 5xx

The status code that the server returns tells us whether the request was successful or not. If the request was successful, the server sends the status code in the range of 200–299. If the request was not successful, then the other status code is returned. You can check the list of most commonly used HTTP status codes along with their description in my previous article HTTP Status Codes

Rest Assured provides a package named “io.restassured.response” which has a Response interface. The Response interface provides methods that can help to manipulate the parts of the received response. The following screenshot shows some of the important methods of the response interface.








When we use the getStatusCode() method, then this will return an integer value, that we can use to validate the response status of the server response. Let’s see its practical use




When we run this Test case, we get below output



Basically, we are using this method to extract the response code

int statusCode= response.getStatusCode();

Then, we are comparing the received status code against the expected value using the below command.

Assert.assertEquals(statusCode,HttpStatus.SC_Ok);

Validating Status code for the Error Scenarios

Till this point, we have discussed the happy flow, the client sends an API request, and in return server returns a successful response with a 200 Status code. But this is not always the case, what if the server we send a request to is not available or does not return a response within the stipulated time, or We do a mistake in passing the address of the resource.

When any of the above scenarios occur, the REST API will return an appropriate status code other than 200. The client in turn has to validate this status code and process it accordingly.

Let’s discuss now how the API will behave and what response it will return in these cases.

Case 1: Here I have intentionally changed the resource address and passed it as “/searchh” instead of “/search”.



If I run this Test, then we receive the below result.

Here, We see that the test returns a status code of 404 but we expected 200. Hence we received an AssertionError. Also, an appropriate Error message is also returned.

Case 2: Now I will use the same code but with the POST HTTP method instead of GET


When we run this test, We see the result as:


Conclusion

Validating HTTP status codes is an essential part of testing REST APIs. Rest Assured provides a simple and expressive way to validate HTTP status codes using the statusCode() method. By using Rest Assured, you can write concise and readable tests that ensure your REST APIs behave as expected.

Ensuring Data Integrity: The Importance of JSON Response Validation

Read JSON response using Rest Assured

Before we dive into the specifics of validating a JSON response body using Rest Assured, let’s briefly discuss what JSON is and why it’s important to validate it.

Today, JSON has become the preferred format for data exchange. With the rise of microservices architecture, the number of APIs being developed and consumed is growing rapidly. As a result, validating the JSON response body has become essential to ensure that the API provides accurate and consistent data.

Validating a JSON response body involves checking that the JSON data conforms to a certain schema. A schema is a set of rules defining the JSON data's structure. It includes information such as the data types, allowed values, and the expected structure of the data.

There are various ways we can validate a response body

  1. Using Assertions:
  2. Using POJO Class Mapping

Assertions

Rest Assured Assertions allow you to check that the response body meets certain criteria. Rest Assured provides some built-in methods like body() for asserting on the response body. Here is an example:

We will use the same API from our previous articles.



In this example, we assert that the JSON response contains the country field in the response body.

Here we can get an object of type ‘io.restassured.response.ResponseBody’. After that using this class, you can validate complete parts of the response body.

How to validate the partial response Body?

Here, firstly we extract the response body in a String format. Then We can use simple String methods to verify the values in the Response. For e.g., we can use the String.contains() method to see if the Response contains a Georg in it. Below is a sample code.



Using POJO

Rest Assured provides support for mapping JSON data to POJO. This allows you to validate the JSON response body by checking the properties of the mapped object.

you first need to define a Java class that represents the JSON data. This class should have properties corresponding to the JSON data fields. You can then use this as a method to map the JSON data to the Java object.




However, there are other better ways we can validate responses. The response interface gives you a mechanism to extract nodes based on a given JsonPath. There is a method called Response.JsonPath(), which returns io.restassured.path.json.JsonPath Object. This object further can be used to query parts of the Response JSON

What is JsonPath?

sonPath is a query language used to extract data from JSON documents. It provides a simple and expressive way to traverse the JSON structure and retrieve the data that you need.

JsonPath expressions are written in a syntax that is similar to JSON, making them easy to read and write

Let’s continue with the same API example response JSON

[
{
"domains": [
"atsu.edu.ge"
],
"country": "Georgia",
"alpha_two_code": "GE",
"state-province": null,
"web_pages": [
"http://www.atsu.edu.ge/"
],
"name": "Akaki Tsereteli State University"
}
]

Here, we will extract the response in the JsonPath object and then querying that object we will reach a specific node which we want to extract.

In the above example, suppose we want to extract the node country. Let’s look at the code now and I would suggest paying attention to the mentioned comments.

In the above example, the response is a List of Universities. Here is sample code to read the nodes from the response using JsonPath.

public class GetUniversityDetails {

@org.testng.annotations.Test
public void getUniversityList() {
Response response;
RestAssured.baseURI = "http://universities.hipolabs.com";
response = RestAssured.given().contentType("application/json")
.queryParam("country", "Georgia")
.when().get("/search");
response.prettyPrint();
//Retrieve the JsonPath object instance from the Response interface
JsonPath js = response.jsonPath();
//Querying the object to reach List of node
List<String> countryList = js.getList("country");
//Iterate the List to get the specific index element. In this case we are retrieving 1 element from the List
String country = countryList.get(0);
//Print the Country value
System.out.println(“Country is “+ country);

}
}
Output when we run the above code and it also prints the Country.


In the similar way you can extract any part of the JSON response.

If you notice in the Response JSON node “web_pages” is again a List. So let’s see now how we can extract the list of all the available values in the list.

public class GetUniversityDetails {

@org.testng.annotations.Test
public void getUniversityList() {
Response response;
RestAssured.baseURI = "http://universities.hipolabs.com";
response = RestAssured.given().contentType("application/json")
.queryParam("country", "Georgia")
.when().get("/search");
//Retrieve the JsonPath object instance from the Response interface
JsonPath js = response.jsonPath();
//Querying the object to reach List of node
List<String> countryList = js.getList("country");
//Iterate the List to get the specific index element. In this case we are retrieving 1 element from the List
String country = countryList.get(0);
//Print the Country value
System.out.println("Country is" + country);
//Querying the object to reach List of node web_pages. Here First we have one list of Universities
// and then another list of webpages
List<List<String>> webPagesList= js.getList("web_pages");
//Iterate the Lists to get the specific index element. In this case we are retrieving 1 list from the set of Lists
List<String> webPage =webPagesList.get(0);
//Print the List of web pages
System.out.println("Webpages available " + webPage);

}

Conclusion

In conclusion, Rest Assured proves to be a valuable tool for validating JSON responses in API testing. It's intuitive syntax and extensive assertion capabilities make it easy to verify the correctness and integrity of JSON structures, data types, and values. By leveraging Rest Assured’s powerful features, we can efficiently handle complex validation scenarios, ensuring that API responses meet the expected criteria.







Throttling of APIs, a recently asked #interview questions:
.
.
𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰𝐞𝐫: how will you explain the throttling of APIs?
𝐂𝐚𝐧𝐝𝐢𝐝𝐚𝐭𝐞: it refers to limiting the number of requests that can be made to an API within a certain timeframe. This is typically done to prevent abuse, ensure fair usage, and maintain the #stability and #performance of the API and the underlying systems.

𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰𝐞𝐫: is there any real-time example?
𝐂𝐚𝐧𝐝𝐢𝐝𝐚𝐭𝐞: Let's say you have an API for retrieving information about movies, and it has a rate limit of 10 requests per minute. If a user or application tries to make more than 10 requests within a minute, the API will start rejecting #additional requests until the minute is over. After that, the user or application can make more #requests, as long as they stay within the rate limit.

For example, if a movie review website allows users to search for movie information using your API, and a particularly #active user tries to make 20 requests within a minute, the API will only respond to the first 10 requests and reject the rest until the next minute begins.

To prevent this, the API provider might implement #throttling rules such as:
𝐑𝐚𝐭𝐞 𝐋𝐢𝐦𝐢𝐭𝐢𝐧𝐠: Limiting the number of requests that can be made within a specific time window, such as allowing only 100 requests per minute.

𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭 𝐂𝐨𝐧𝐧𝐞𝐜𝐭𝐢𝐨𝐧 𝐋𝐢𝐦𝐢𝐭: Limiting the number of simultaneous connections that can be made to the API server.

𝐔𝐬𝐚𝐠𝐞 𝐐𝐮𝐨𝐭𝐚𝐬: Setting a maximum number of requests that can be made within a certain period, such as 1000 requests per month per user.

===============================================

Generate OAuth token for Github:

1)go to github.com-->settings-->developer settings-->click on oAuth-->register application and get the client id and then generate client secret in github itself

then go to url in the browser https://github.com/login/oauth/authorize/client_id

it will give the auth code, this auth code is temporary/expire then generate same way


Started a short practical series on Data-Driven Testing in Postman :
1). Using CSV
2). Using JSON

I've uploaded the first two videos. If you’re looking to learn how to run API tests with different data sets, these short videos can help. Whether you’re preparing for an interview or just refreshing your skills, they can be useful.
https://www.youtube.com/watch?v=GjGFRpSxkd0&list=PLUPlX-9QUIrMPt5F1EP3UyJWsbz8J2DQc

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.