image

How to test API Endpoints

Introduction

 

An API (Application Programming Interface) is a software intermediary that allows two applications to communicate with each other. The communication between applications occurs through requests and responses. When a client application wants to interact with a service-providing application, it sends an API request to the service provider via an API endpoint. The service providing application process the API request and sends back a response to the client application. This is the fundamental mechanism of an API. Let's explore some API concepts and API testing procedures. 

API Glosarry

 

Before getting into API testing, we need to understand some of the key concepts in API such as API endpoint, HTTP Methods, Authorization, Request, Response and HTTP Status code. Let's explore one by one. 

API Endpoint

 

An API endpoint is an URL. It acts as a connector between client application and service providing application. Each endpoint corresponds to a particular function or resource of the API. We can define the API function with HTTP methods. 

HTTP Methods

 

APIs can perform various actions such as retrieving, creating, updating and deleting data. These actions are defined by HTTP methods. Here is the list of HTTP methods that are most commonly used.

GET: This HTTP method is used to retrieve data from the service provider. If the service providing application accepts the client GET’s request, then it will return the response in HTML or JSON or XML or in other formats.

POST: Post method is typically used to create a new record in the database based on the data included in the request body.

PUT: This method is used to update an existing record with a new record.

PATCH: PATCH is used to update or modify the existing data. This method is similar to the PUT method. The difference is the PUT method updates the entire record and creates a new version of it, while PATCH update required part of the resources. For example, if we have a user resource with fields for name, email, and password, and we need to update the password only, we can use the PATCH method. 

DELETE: As the name says this method is used to delete the existing data on the database.

HEAD: This method returns the metadata of the resource such as size, modification data without retrieving the actual data. This method can be used to check that the DB has the required resource.

OPTIONS: This method returns the communication options for the targeted resources such as HTTP method and other options supported by the resources. This method is primarily used for CORS (Cross-Origin Resource Sharing) preflight requests.   

API Authentication and Authorization

 

To access an API, API authentication and API authorization processes are used. Although these two processes might sound similar, they serve different purposes. 

API Authentication:  Is the process of verifying the identification of the User or the system that makes the request. Common authentication types are HTTP basic Authentication, JWT (JSON Web Token) Authentication and OAuth. 

API Authorization: This process works as an access control. It checks whether the authenticated user has required permission to perform a specific action or access a particular resource. 

During API authentication and authorization process, the API may provide an API key or an Access token based on the type of authentication used.  These keys and tokens are typically passed in request headers to authenticate users and authorize access to the API’s resource.

API Request and Response

 

Now, we understand API endpoints, HTTP Methods, and the authentication and authorization process. We can combine these elements to create an API request. 

An API request is also called an API Call, is a message that is sent to an API to request data, functionality or a service. 

In the API call, the endpoint identifies the specific resource or a service on the server, the HTTP method defines the action to be performed and the header includes information like the authentication key or token.

After the server processes the request. It sends a response back to the client. This response includes an HTTP Status code which indicates the result of the request, Response Body that contains the requested data or confirmation message or a message of error that is encountered. 

HTTP Status Code

 

Every API request receives an HTTP status code with their responses. This status code indicates when the operation is successful or failed or encountered any error from server side or from client side. These Status code is grouped in five classes.

- Informational responses (1xx)

- Successful responses (2xx)

- Redirection messages (3xx)

- Client error responses (4xx)

- Server error responses (5xx)

Here is some of the common HTTP Status Code.

200 OK: Standard response for a successful request.

400 Bad Request: The request has bad syntax or the server is unable to process the request due to an invalid input or error from the client side.

401 Unauthorized: The client doesn’t have authorization to process this request.

403 Forbidden: The authorization credentials sent from the client are not allowed or invalid to process the request.

404 Not Found: The server has not found anything matching the URI provided.

422 Unprocessable Entity: The action could not be processed properly due to invalid data provided from the client side.

500 Internal Server Error: The server encountered an unexpected condition and was unable to fulfill the requested action.

502 Bad Gateway: Indicates a problem with communication between servers when attempting to load a web page.

503 Service Unavailable: The server is temporarily unable to handle your request.

API Endpoint Testing Procedure

 

API testing is a type of software testing that validates functionality, performance, reliability and security of the API endpoints. The Testing process involves sending the API request to the server and validating the response data is displayed as per spec file. Here's a general approach to API testing.

Understand API Specifications:

 

Before starting the testing process, we need to understand the API documentation. This documentation typically includes the purpose of the API endpoint, its user story, parameter, authentication methods, expected responses and its error codes. From this documentation we can understand the functional and non-functional required of the API endpoint.

Define Test Cases:

 

Based on the API documentation, we can define test cases for the API endpoint.

>Create positive test cases with valid inputs where the API is expected to return successful responses.

>Create negative test cases with invalid inputs, missing parameters, or wrong HTTP methods where the API is expected to return correct HTTP status code and valid error messages.

>Write test cases to ensure that the API will not give response against common vulnerabilities such as Unauthorized access, SQL injection, and XSS.

Setup Test Environment and Define testing tools.

 

After defining what is going to be tested, select the appropriate API testing tool. Tools like Insomnia, Postman, or Curl are commonly used. Confirm that the test environment is working perfectly.

Execute the Functional Test Cases

 

We have test cases, test environments and tools for testing, now start testing the API endpoints using selected tools. Initially test all the functional test cases by manually sending API requests and validating the responses against the specification file.

In this process ensure that

>The API returns the appropriate HTTP status code.

>The response structure matches the documentation.

>The response data is consistent with the request parameters.

>The API handles errors gracefully, providing meaningful error messages and appropriate status codes.

Conduct Non-Functional Testing 

API Performance Testing

 

API performance testing is a process of evaluating speed, reliability and stability of the API endpoint under different data loads. This testing process involves measuring API call response time, the amount of data processed in a given period of time, conducting load test and stress tests to assess scalability and error rates. Performance testing helps to identify bottlenecks and  optimizing APIs helps to ensure that applications run smoothly and efficiently.

API Security Testing

 

API security testing ensures that APIs are protected from vulnerabilities and unauthorized access. Attackers can exploit APIs by injecting malicious code to manipulate databases, servers, or the API's intended behavior. Which makes it crucial to test APIs against threats like SQL injection and Host-Header Injection, and ensure that sensitive data is encrypted properly. 

Review and Report the Test Results

 

After completing the testing process, review the test results. Document if any bugs found in the testing process and report it to the development team. After fixes are applied, retest the API endpoint to ensure that the issues have been resolved.

API Automation

 

Some Applications might have hundreds of complex APIs, manually re-testing each API endpoint after every update is time-consuming. To streamline this process, API automation becomes handy. We can automate API testing using frameworks like Postman Collections, Newman, or any other automation framework. Automated testing supports CI/CD, allowing us to identify and fix issues quickly. Additionally, API automation can simulate various scenarios, including performance and security tests, ensuring the API remains reliable and secure under different conditions.

Key areas to Concentrate during API Testing. 

 

>Verify that the response body data matches the documentation.

>Verify that a valid error message is provided in the response body, along with the appropriate HTTP status code, when an incorrect API endpoint path is given.

>Ensure that the response is generated only for the correct HTTP method as specified in the documentation, and that an error message is returned when a different HTTP method is used.

>Verify that the API does not return the requested response data and provides a valid error message and HTTP status code when the Bearer Token or Authorization key is invalid or not given at all. 

>Verify that all API parameters correctly filter data and provide the appropriate HTTP status code and error message in the response body when invalid parameters are provided.  

>Check performance of the API under high traffic and large data loads to evaluate response times. 

>Ensure that the API supports pagination, returning the correct data for each page requested, and verify that invalid pagination inputs return an error message and proper HTTP status code.

Conclusion:

 

API testing is crucial for performance, security and reliability of the application. By defining comprehensive test cases based on the API specifications and using appropriate testing tools we can effectively validate that the API endpoint meets both functional and non-functional requirements. API Automation improves the efficiency of the testing process. As applications grow in complexity, robust API testing processes and automation practices become increasingly critical to maintaining the quality and reliability of your software.