API Testing
API Testing
What is Server?
Server is a software which manages all the resources along with which the
process the client request and serve the client request.
1. Database Server
2. Application Server
3. Web Server
Example: Apache POI, Jboss, IBM WebSphere, Oracle web logic etc.,
Ans: An application which performs all three different types of logics such as:
1. Presentation logic
2. Persistence logic
3. Business logic
Static Resources: Resources are which are capable of dealing with only static
data [which can’t be changed] are known as “static resources”.
Dynamic Resources: Resources which are capable of dealing with only dynamic
data [which can be change] are known as “Dynamic Resources”.
Business logic performs core functionality i.e., some set of calculation and
validation operation on an application.
Technologies involved - Servlet, Spring etc.,
Note: A Dynamic application or Real time application is an Integration
[Combination] all the three different types of logic such as Presentation logic,
Persistence logic and Business logic.
What is Session?
Any activity which takes place between the start time and stop time is known as
“Session”.
What is Caching?
Types of Cache:
Speed: The client gets the response much faster because the server is
skipped for repeated requests.
Reduced Load: The server doesn’t have to process the same requests over
and over.
Efficiency: Network traffic is reduced because fewer requests are sent to
the server.
GET Request
What is GET Request?
GET is used when you want to fetch or retrieve data from a server. This
could be any kind of data,
such as:
o Information about a resource (e.g., users, products, posts).
o Data reports or analytics.
o Metadata about a system or service.
GET requests do not alter data on the server. This is ideal for scenarios
where you only need to read or view information, not create, update, or
delete.
Many APIs and web servers cache GET requests, making them faster. This is
because the same request will typically return the same data without
needing to interact with the server again.
GET requests are stateless. The server does not store information about the
request after the response is returned.
o Data Retrieval,
o Non-Modifying Operation,
o Caching Support,
o Stateless Communication.
Library RequestsLibrary
${BASE_URL} https://jsonplaceholder.typicode.com
Log ${response.json()}
Explanation:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
if response.status_code == 200:
You should use GET requests whenever you need to retrieve data without altering
the server's state.
Querying Data:
GET requests can include parameters to filter or query data, like: /users?
age=25&location=NYC to get users aged 25 in New York City.
In web development, GET requests are used to load pages or data (e.g.,
loading a user’s profile).
Public APIs:
Many public APIs (like weather, news, or stock market data) provide data
via GET requests.
Examples: /weather/today to retrieve the current weather.
/stocks/GOOGL to retrieve stock prices for a company.
When you need to filter or search for specific data (e.g., search for items by
category, date, or any specific attribute).
When you need to access data that is publicly available (e.g., fetching
weather data or news feeds).
When you're testing APIs, you can use GET requests to validate that data is
being retrieved correctly.
Can you explain the difference between GET and POST requests?
1. GET requests retrieve data without modifying it, while POST requests
send data to the server to create resource.
2. GET requests can include parameters in the URL, whereas POST requests
typically send data in the request body.
How would you check the response status code of a GET request?
You can access the status_code attribute of the response object. For example:
Should Be Equal As Numbers ${response.status_code} 200
What are some common HTTP headers you would use with a GET request?
Common headers include:
Accept: Specifies the content types the client can process (e.g.,
application/json).
Authorization: Used for authentication, often containing tokens or credentials.
Cache-Control: Directives for caching mechanisms.
Can you give an example of using a GET request in Robot Framework to fetch
user details?
You can demonstrate a test case that retrieves user details using a GET
request, validating the response:
*** Test Cases ***
Get User Details
Create Session my_session https://jsonplaceholder.typicode.com
${response}= GET my_session /users/1
Should Be Equal As Numbers ${response.status_code} 200
Should Be Equal ${response.json()['username']} 'Bret'
What would you do if the GET request returns a 404 status code?
I would investigate the endpoint to ensure it is correct, check if the resource
exists, and possibly log the error for further analysis. Depending on the
situation, I might implement error handling to manage such cases in my tests.
If a GET request takes a long time to respond, how would you handle it?
You could implement timeout settings in your GET request and add error
handling to retry the request or log the issue. For example:
${response}= GET my_session /posts/1 timeout=10
POST Request
What is a POST Request?
API Testing for Web Applications: Whenever you need to create or modify
data on the server, such as submitting a form, uploading a file, or posting
comments in a forum.
Automation of CRUD Operations: In testing APIs that involve Create
operations (in Create, Read, Update, Delete - CRUD), POST is essential for
automating these tests.
Integration Testing: POST requests are used in testing workflows where an
API creates resources that are then validated by further actions (e.g.,
retrieving data or updating data).
When Testing APIs That Create Data: POST is used when testing operations
that create new entities in the system, such as a new user or transaction.
When You Have Data to Send in the Request Body: POST requests allow
you to send structured data (like JSON or XML) in the request body, which
is necessary when the API requires complex input data.
For Testing Stateful Operations: Since POST requests often change the
state of the server (like creating an order in an e-commerce system), use
them when you need to test state-changing operations.
Key Points on POST Request:
Use: POST requests are used when testing APIs that involve creating or updating
resources on the server.
Why to Use: It allows sending structured data to create new resources and
perform non-idempotent operations.
Where to Use: POST requests are essential in testing the create (C) part of CRUD
operations in API testing.
When to Use: Use POST when you have to send large payloads in the request
body, modify the server state, or test API endpoints that involve data submission.
PUT Request
What is PUT?
Use PUT when interacting with RESTful APIs in situations where you need
to:
Update an existing resource (such as updating user details, modifying a
product, etc.).
Ensure that multiple identical requests don’t cause unexpected results.
Create resources with a client-specified ID (if the resource doesn’t exist).
Summary
You need to update an employee’s name from deva to Devender for the
employee with emp_id = 1. This can be done with a PUT request because
you're replacing the existing employee's information with new data.
If the employee does not exist, the same PUT request can be used to create
a new employee record with emp_id = 1 and name = Devender.
emp_id: 204
name: “Kesav”
The original resource for emp_id = 204 might look like this:
“emp_id”: 204,
2. PUT Request
If you want to update the employee’s details to, say, a new name “Keshav” and
perhaps change the position and department as well, you would send a PUT
request with the full updated employee object:
PUT /employees/204
Content-Type: application/json
“emp_id”: 204,
3. Expected Behavior
After successfully sending the PUT request, the updated resource on the server
would now look like this:
“emp_id”: 204,
“name”: “Keshav”,
“department”: “Development”
The PUT and PATCH methods are both used to update resources in RESTful APIs,
but they differ significantly in how they perform those updates.
4. Purpose
PUT: The PUT method is used to update an existing resource or create a
new resource if it does not exist. It requires the complete representation of
the resource being updated.
PATCH: The PATCH method is used to apply partial modifications to a
resource. It only requires the fields that need to be updated, rather than
the complete resource.
5. Request Body
PUT: The request body must contain the entire updated resource. If any
fields are omitted, they may be cleared or set to default values on the
server.
Example: Updating a user profile:
PUT /users/123
{
“id”: 123,
“name”: “John Doe”,
“email”: “john@example.com”
}
PATCH: The request body contains only the fields that need to be changed.
This makes it more efficient for updates.
Example: Updating just the user’s email:
PATCH /users/123
{
“email”: “john.doe@example.com”
}
3.Idempotence
PUT: PUT is idempotent, meaning that making the same PUT request
multiple times will have the same effect as making it once. If you send the
same data again, it will not change the resource further.
PATCH: PATCH is not necessarily idempotent, as applying the same patch
multiple times may result in different outcomes. For example, if you PATCH
a counter field, the value may change with each request.
6. Use Cases
PUT: Use PUT when you need to replace an entire resource or ensure that
the resource has a complete and specific state. Common in situations
where the resource is small and can easily be sent in full.
PATCH: Use PATCH when only a few fields of a resource need to be
updated. It is particularly useful for large resources where only minor
changes are necessary. Ideal for frequent updates, as it reduces data
transfer.
7. Server Behavior
PUT: If the resource does not exist, the server may create it based on the
request body.
PATCH: The server will only modify the fields specified in the request body.
Other fields remain unchanged.
PATCH Request
What is PATCH?
Efficiency: Since only the changes are sent to the server, it minimizes the
amount of data sent over the network, making it more efficient.
Flexibility: Allows partial updates without needing to resend the entire
resource, which can be beneficial for large resources.
Better Performance: Reduces server load and bandwidth usage, especially
for applications where frequent updates are necessary.
Where to Use PATCH?
emp_id: 204
name: “Kesav”
The original resource (for emp_id = 204) might look something like this in
JSON format:
{“emp_id”: 204, “name”: “Kesav”, “position”: “Engineer”, “department”:
“IT” }
PATCH Request
You would send a PATCH request to update only the name field:
PATCH /employees/204
Content-Type: application/json
{
“name”: “Keshav”
Expected Behavior
After successfully sending the PATCH request, the updated resource on the server
might look like this:
“emp_id”: 204,
“position”: “Engineer”,
“department”: “IT”
DELETE Request
What is DELETE?
such as:
When Data is No Longer Needed: Use DELETE when you have confirmed
that the resource is no longer needed or is obsolete.
When a User Requests Deletion: Often used in scenarios where a user
requests to remove their data or any specific resource.
During Maintenance: Use DELETE during maintenance activities to remove
unnecessary or temporary data.
HEAD Request
What is HEAD?
The HEAD method is an HTTP request method used to retrieve the headers of a
resource without fetching the body of the resource. It’s similar to the GET
request, but it only returns the response headers, not the actual data.
Efficiency: Since HEAD requests do not return the body of the resource,
they are generally faster and consume less bandwidth, making them ideal
for checking resource availability and metadata without downloading the
entire resource.
Caching: It can be used to check if the cached version of a resource is still
valid, as the headers often contain cache-related information.
Validation: Useful for checking if a resource exists before making a full GET
request, allowing for quick validation of URLs or endpoints.
Summary
HEAD is an efficient method to retrieve metadata about a resource without
downloading it.
Use it for checking resource availability, inspecting headers, and optimizing
performance.
Easily implemented in Robot Framework using the RequestsLibrary or
through custom Python keywords.
Interview Questions
What is REST, and how does it work?
It relies on stateless communication and uses standard HTTP methods like GET,
POST, PUT, DELETE to perform operations on resources, which are identified by
URLs (URIs).
What are the main HTTP methods used in REST APIs, and what do they do?
Get is used to retrieve data from the server and Post is used to submit data
to the server, to create a new resource in server.
GET: Data is sent as part of the URL in the query string (e.g., ?name=value)
and Post: Data is sent in the body of the request, not in the URL.
Because the data is included in the URL, there are length limits, and it’s not
suited for sending large data and There is no size limit on the body data, so
it can handle large payloads (e.g., files or form data).
Data is visible in the URL, making it less secure for sensitive information
like passwords or personal data and Data is sent in the body, which is not
directly visible in the URL, making it more secure for sensitive data.
GET is idempotent, meaning multiple identical GET requests will have the
same effect (i.e., fetching the same resource without any side effects) and
POST is not idempotent, meaning each POST request could have different
effects, such as creating a new resource or triggering an action on the
server.
What is the difference between a POST and PUT request in REST API, and how
can you implement both in Robot Framework?
Answer: Using the RequestsLibrary, you can perform a GET request like this
Library RequestsLibrary
Log ${response.status_code}
Log ${response.json()}
How can you verify the status code of an API response in Robot Framework?
Answer: You can verify it using the Should Be Equal As Numbers keyword
How do you send headers and payload in a POST request in Robot Framework?
Answer: You can add headers and payload using the json or data arguments along
with Create Dictionary for headers.
How can you handle dynamic URLs in Robot Framework for API requests?
Answer: You can parameterize the URL by passing variables into the request.
Answer: You can use the Should Be Equal or Should Contain keyword to validate
the JSON response.
How many status code are there of an API response in Robot Framework?
HTTP status codes are grouped into five categories, and there are many specific
codes under each category.
There are over 60 standard HTTP status codes across the different categories.
Should Be Equal
${response.content}:
${response.text}:
This attribute contains the decoded response content as a string, using the
appropriate character encoding (e.g., UTF-8).
It is typically used when you expect a textual response, such as JSON,
HTML, or plain text, and you want to work with it as a string.
It automatically handles the decoding of bytes to a string based on the
content type specified in the response headers.
Key Differences:
Use Case: Use ${response.content} for binary data and ${response.text} for
textual data.