What is API Testing?
API testing involves verifying that APIs function as expected. It is performed to
ensure the API delivers the right output, handles error scenarios,
and behaves as required under various conditions.
Unlike UI testing, which deals with user interfaces, API testing focuses on the
business logic layer where APIs interact with databases, servers, and other
systems.
Why is API Testing Important?
APIs are the backbone of modern applications. Ensuring they work correctly means
ensuring the functionality of entire systems.
API testing is faster than UI testing and more reliable because you can directly
test the logic and data processing behind the scenes.
Types of APIs
REST APIs:
REST stands for Representational State Transfer. It’s an architectural style for
distributed hypermedia systems.
Stateless: Each request from client to server must contain all the information the
server needs to fulfill the request.
Uses HTTP as the communication protocol.
Data Format: Typically returns data in JSON or XML format.
SOAP APIs:
SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured
information in the implementation of web services.
It relies on XML for data formatting.
Stateful: Can maintain the state between requests.
Supports more extensive security features, including WS-Security.
Endpoints : Different location/address within the API where we get data.
HTTP Methods:
GET: Fetches data from the server (read operation).
POST: Sends data to the server (create operation).
PUT: Updates data on the server (replace operation).
PATCH: Partially updates data on the server.
DELETE: Removes data from the server.
OPTIONS: Returns supported HTTP methods for a resource.
HEAD: Similar to GET, but without the response body.
### 1. **GET Request**
The **GET** method is used to retrieve data from the server.
#### Example: Getting User Information
Imagine you have an API that provides information about users. Let's say the URL is
`[Link] to get information about the user with ID `1`.
- **Method:** GET
- **URL:** `[Link]
- **Headers:** (If needed) You can add headers like `Authorization: Bearer <your-
token>` if the API requires authentication.
- **Response:** The server will return the user data (e.g., name, email, etc.).
#### Steps in Postman:
1. Select the **GET** method from the dropdown.
2. Enter the URL `[Link]
3. Click **Send**.
4. View the response in the **Body** tab, where you’ll see the user details
returned in a JSON format, such as:
```json
{
"id": 1,
"name": "John Doe",
"email": "[Link]@[Link]"
}
```
---
### 2. **POST Request**
The **POST** method is used to send data to the server to create a new resource.
#### Example: Creating a New User
Imagine you want to create a new user using an API.
- **Method:** POST
- **URL:** `[Link]
- **Body:** You will need to provide the user data in JSON format. For example:
```json
{
"name": "Alice",
"email": "alice@[Link]"
}
```
#### Steps in Postman:
1. Select the **POST** method from the dropdown.
2. Enter the URL `[Link]
3. Select the **Body** tab below the URL field.
4. Choose the **raw** radio button and select **JSON** from the dropdown.
5. Enter the JSON data in the body:
```json
{
"name": "Alice",
"email": "alice@[Link]"
}
```
6. Click **Send**.
7. View the response, which should include the details of the newly created user.
For example:
```json
{
"id": 2,
"name": "Alice",
"email": "alice@[Link]"
}
```
---
### 3. **PUT Request**
The **PUT** method is used to update a resource on the server, typically by
replacing the entire resource.
#### Example: Updating an Existing User
Suppose you want to update the user's information with ID `1`.
- **Method:** PUT
- **URL:** `[Link]
- **Body:** The entire updated user data (e.g., updating the name and email):
```json
{
"name": "John Smith",
"email": "[Link]@[Link]"
}
```
#### Steps in Postman:
1. Select the **PUT** method from the dropdown.
2. Enter the URL `[Link]
3. Select the **Body** tab below the URL field.
4. Choose the **raw** radio button and select **JSON** from the dropdown.
5. Enter the updated JSON data in the body:
```json
{
"name": "John Smith",
"email": "[Link]@[Link]"
}
```
6. Click **Send**.
7. The server should respond with a success message, such as:
```json
{
"id": 1,
"name": "John Smith",
"email": "[Link]@[Link]"
}
```
---
### 4. **PATCH Request**
The **PATCH** method is used to make partial updates to a resource. Unlike **PUT**,
which replaces the entire resource, **PATCH** only updates the fields that you
specify.
#### Example: Updating Part of a User's Information
Suppose you want to update only the email of the user with ID `1`.
- **Method:** PATCH
- **URL:** `[Link]
- **Body:** You only include the field you want to update, in this case, just the
email:
```json
{
"email": "[Link]@[Link]"
}
```
#### Steps in Postman:
1. Select the **PATCH** method from the dropdown.
2. Enter the URL `[Link]
3. Select the **Body** tab below the URL field.
4. Choose the **raw** radio button and select **JSON** from the dropdown.
5. Enter the partial update JSON data in the body:
```json
{
"email": "[Link]@[Link]"
}
```
6. Click **Send**.
7. The server should respond with the updated user information. For example:
```json
{
"id": 1,
"name": "John Smith",
"email": "[Link]@[Link]"
}
```
---
### Summary of the Methods:
- **GET:** Retrieve data (e.g., user details).
- **POST:** Create new data (e.g., create a new user).
- **PUT:** Update data by replacing the entire resource (e.g., update all user
details).
- **PATCH:** Partially update data (e.g., update only a single field like email).
These examples should help you get started with making API requests using Postman!
HTTP Status Codes:
200 OK: Successful request.
201 Created: Resource created successfully.
400 Bad Request: Invalid request format.
401 Unauthorized: No authentication or invalid credentials.
403 Forbidden: The server understood the request but refuses to authorize it.
404 Not Found: The resource does not exist.
500 Internal Server Error: Server error while processing the request.
API Request components :
Address (URI)
Request HTTP method
Request Header
Request Body
API Response Components:
Response Body: The actual data returned by the API, usually in JSON or XML format.
Response Headers: Metadata about the response, such as content type or
authentication details.
Status Code: Indicates whether the request was successful or not.
Cookies: Sometimes APIs return cookies to maintain stateful sessions.
Types of Testing in API
Functional Testing: Ensures the API performs as expected and returns the correct
responses for given inputs.
Security Testing: Verifies that the API has proper authentication and authorization
mechanisms.
Load/Performance Testing: Ensures the API can handle a large number of requests
simultaneously.
Negative Testing: Involves testing invalid inputs or edge cases to ensure the API
behaves correctly under abnormal or erroneous conditions.
ex : Sending an empty payload or invalid JSON in a POST request.
Error Handling Testing: Verifies how the API responds to invalid requests, such as
returning appropriate status codes and error messages.
Data Integrity Testing: Ensures that the data returned by the API is consistent,
accurate, and complete.
Example: Testing the creation, retrieval, update, and deletion of data through the
API.
Versioning Testing: Verifies backward compatibility when API versions change.
Ensures that older versions of the API continue to function as
expected even when new versions are released.
Best Practices for API Testing
Test Valid and Invalid Inputs: Ensure that you test APIs with both valid and
invalid inputs to verify the error-handling capabilities.
Test Different HTTP Methods: Make sure to test all the possible HTTP methods
(GET, POST, PUT, DELETE, etc.) to ensure all operations work as intended.
Check Authentication & Authorization: Verify that authentication mechanisms like
API keys, OAuth, or JWT tokens are correctly implemented.
Verify Response Format: Ensure the response format (JSON, XML) is correct and
adheres to the expected schema.
Validate data types, field names, and required fields in
the response.
Automation: Automate API tests wherever possible using tools like Postman, Rest
Assured, or SoapUI to reduce human errors and increase efficiency.
Integrate API tests into CI/CD pipelines for continuous validation.
Authentication methods
1. Basic Authentication
Overview:
Basic Authentication is a simple authentication method where the client sends a
username and password in the HTTP header.
The credentials are combined as username:password and encoded using Base64.
Ex : GET /api/user
Authorization: Basic dXNlcjpwYXNzd29yZA==
2. Bearer Token Authentication (OAuth 2.0)
Overview:
Bearer Token authentication uses an access token (typically a JWT or OAuth token)
that is included in the request header to authenticate the user.
This token is generated after the user successfully logs in or after authorization
via an OAuth flow.
Ex : GET /api/user
Authorization: Bearer <JWT_token>
3. OAuth 2.0 (Authorization Code Flow)
Overview:
OAuth 2.0 is a more secure and flexible authorization framework. It allows third-
party applications to gain limited access to an HTTP service.
How it works:
The client sends the user to the authorization server (e.g., Google, Facebook) for
login.
Once authorized, the client receives an authorization code.
The client exchanges the code for an access token.
The token is then used for API calls.
4. API Key Authentication
Overview:
An API key is a unique identifier sent in the request to authenticate the client.
The key is typically included in the query string or header, depending on the API
specification.
How it works:
The client includes the API key either in the header or as a query parameter.
In Header: Authorization: ApiKey <your_api_key>
In URL: [Link]
Ex : GET /api/user?api_key=your_api_key
Request Parameters
1. Query Parameters
Definition: These are parameters that are appended to the URL of an API request.
They are typically used to filter, sort, or paginate the results.
Location: They appear after a question mark (?) in the URL.
Format: They are represented as key-value pairs, separated by an = sign, and
multiple parameters are separated by an &.
Example URL with Query Parameters:
GET /api/users?age=25&location=NY
2. Path Parameters
Definition: These parameters are part of the URL itself and are used to identify
specific resources.
Location: They are embedded in the URL and are enclosed in curly braces ({}) in the
documentation.
Example URL with Path Parameters:
GET /api/users/{user_id}
One use case : Ensure that the API returns the appropriate HTTP status code (e.g.,
404 Not Found for an invalid user_id).
3. Header Parameters
Definition: These parameters are included in the request's headers, often used for
providing metadata such as authentication tokens, content type, or custom
information.
Location: Sent as key-value pairs in the HTTP request header.
Example Request with Header Parameters:
GET /api/users
Authorization: Bearer <JWT_token>
Content-Type: application/json
4. Body Parameters
Definition: These are parameters included in the body of the request, typically
used in methods like POST, PUT, or PATCH to send data to the server.
Location: The body is part of the request and is usually sent as JSON or XML.
Example Request with Body Parameters (JSON format):
POST /api/users
{
"username": "john_doe",
"email": "[Link]@[Link]",
"password": "securepassword123"
}
Best Practices in API Testing
Consistency and Reusability: Writing reusable test cases that can be run across
different environments.
Environment Setup: Ensuring the testing environment mirrors the production
environment to reduce discrepancies.
Test Data Management: Managing test data to ensure a consistent and controlled test
environment (e.g., handling stateful data, clean-up of data after tests).
Reporting and Logging: Collecting comprehensive logs and reports for better
analysis of test results and identifying issues.