The Katalon Blog

What is API Testing? A Complete Guide To Test APIs

Written by Katalon Team | Apr 10, 2024 9:20:00 AM

APIs are the backbone of the digital world. Every time you use an application such as Facebook or Instagram, or even check the weather, it is likely that some APIs are at work. They are the middleman of apps and web services, and API testing is crucial to ensure that this middleman works seamlessly.   
 

In this article, we’ll explore the concept of API testing in depth. We’ll also show you how easy and simple it is to automate API testing with just a few steps.

 

What is API Testing?

Let’s start with the fundamentals.   
 

API testing is a comprehensive process to evaluate an API in terms of its functionality, security, and performance under various conditions, and more.   
 

To learn more about the concept of an API, have a look at this article: What Are APIs + 10 Popular Examples?   
 

Simply put, an API allows applications and software components to transfer data with each other. Think of app A as having a special function, like a unique filter. App B can't directly use that filter, but if app A provides an API, app B can access and use the filter through the API, as if it were its feature.   
 

API testing ensures it can provide the right data, at the right time, in the right format, at the expected performance or not.

 

 

Anatomy of an API

This is how an API response looks like:


 

So, how does requesting an API happen?

  1. The process of requesting an API begins when the client initiates an action that requires data from an API. This action can be many things: clicking a button, submitting a form, or triggering part of a multistep workflow within the application.
  2. The request is then constructed with an endpoint URL that you need to access. Each endpoint URL of an API provides a specific functionality for you to retrieve. For example, if you are testing an e-commerce website, and you want to extract information about a product in the Electronics category, the URL may look something like: https://ecommercewebsite[dot]com/products?category=electronics.
  3. You also need to specify the HTTP method to be performed on the API server. You can read the API documentation to have a better understanding of which methods are supported. Some of the most common methods include:
    • GET: retrieve data
    • POST: create data
    • PUT/PATCH: update data
    • DELETE: remote data
  4. If the API endpoint requires any parameters to be included in the request, specify them according to the documentation.   
     

Let’s have a look at an API request using the popular JSONPlaceholder API, which provides fake JSON data for testing and prototyping purposes. We'll make a GET request to retrieve a list of posts from the /posts endpoint.

 

import requests
        # Base URL of the JSONPlaceholder API
        base_url = “https://jsonplaceholder.typicode.com”
        # Endpoint to retrieve posts
        endpoint = “/posts”
        # Construct the full URL
        url = base_url + endpoint
        # Make the GET request
        response = requests.get(url)
        # Check if the request was successful (status code 200)
        if response.status_code == 200:
            # Extract the JSON data from the response
            posts = response.json()
            
            # Print the list of posts
            for post in posts:
                print("Post ID:", post["id"])
                print("Title:", post["title"])
                print("Body:", post["body"])
                print()
        else:
            print("Error:", response.status_code)
        

In this request, you can see the Base URL and the endpoint are connected to create the full URL. We then make a GET request on the URL to extract the data we want. Here we have retrieved the Post ID, Title, and Body.   
 

API testing is essentially checking if every part of the API is working well.

Benefits of API Testing

  1. Language-independent: Data is exchanged via XML and JSON formats, so any language can be used for test automation. XML and JSON are typically structured data, making the verification fast and stable. There are also built-in libraries to support comparing data using these data formats.
  2. GUI-independentAPI testing can be performed in the app prior to GUI testing. Early testing means timely feedback and better team productivity. The app's core functionalities can be tested to expose small errors and to evaluate the build's strengths.
  3. Improved test coverage: Most API/web services have specifications, allowing you to create automated tests with high coverage — including functional testing and non-functional testing.
  4. Faster releaseExecuting API testing saves up to eight hours compared to UI testing, allowing software development teams to release products faster.

 

Check Out Top API Testing Tools On The Market
 

API Test Case Examples

When testing APIs, it is important to cover all of its aspects. Usually, there are three primary areas you will want to look at:

  1. Functionality
  2. Security
  3. Performance

Let’s take a look at some examples for each category in the table below:   
 

Category

Test Case Description

API functional testing

Verify that the API endpoint "/users" returns a list of users.

Test the POST method on the "/users" endpoint to create a new user.

Validate that required fields such as username and email are mandatory when creating a new user.

Test the API's handling of pagination parameters for large data sets returned by the "/users" endpoint.

Verify that the API returns an appropriate error response with a meaningful message when a user is not found.

API security testing

Attempt to inject SQL queries into API input parameters to test for SQL injection vulnerabilities.

Test for sensitive data exposure by inspecting API responses for any leakage of personally identifiable information (PII).

Validate that the API requires authentication tokens for accessing sensitive endpoints such as "/admin".

Test for XSS vulnerabilities by injecting JavaScript code into input fields and checking API responses.

Verify that rate limiting is enforced to prevent brute-force attacks on user authentication endpoints.

API performance testing

Measure the average response time of the "/users" endpoint under normal load conditions.

Conduct load testing by simulating a large number of concurrent requests to the API to assess its scalability.

Test the response time of the API endpoint "/products" under peak load conditions during a flash sale event.

Verify the API's concurrency handling by sending multiple simultaneous requests to the "/orders" endpoint and checking for data consistency.

Identify performance bottlenecks by monitoring server CPU and memory usage during stress testing with high request volumes.

 

You may be interested: Top Test Cases for API Testing (With Test Case Template)

 

 

API Testing Types

Of course, API testing is not limited to the three areas listed above. There are many more types to take into consideration, including:   
 

  1. Validation testing: Validation testing occurs among the final steps of verification and plays an essential role in the development process. It verifies aspects of the product, behavior, and efficiency. In other words, validation testing assures correct development.   
     
  2. UI testing: UI testing evaluates the user interface (UI) for the API and other integral parts, focusing more on the API than API testing. Although UI testing is not a specific test of API in terms of codebase, this technique still provides an overview of the health, usability, and efficiency of the app’s front and back ends.   
     
  3. Load testing: Load testing generally occurs after a specific unit or the whole codebase has been completed. This technique checks if the theoretical solutions work as planned. Load testing monitors the app's performance at both normal and peak conditions, and is a smaller subset of performance testing.   
     
  4. Penetration testing: Penetration testing is typically considered the second test in the auditing process. In this type, users with limited API knowledge will try to assess the threat vector from an outside perspective, which covers functions, resources, and processes, or aims to address the entire API and its components.   
     
  5. Runtime and error detection: This testing type relates to the actual running of the API, with a focus on the universal results of utilizing the API codebase. This technique hones in on one of the following aspects: monitoring, execution errors, resource leaks, or error detection.   
     
  6. Fuzz testing: Fuzz testing is another step in the security audit process. In fuzz testing, a vast amount of random data (referred to as "noise" or "fuzz") is input into the system to detect any forced crashes or negative behaviors. This technique tests the API’s limits to prepare for the “worst-case scenarios.”

 

Read More: How To Go From Manual Testing to Automation Testing?

API Testing: A How-To Guide

Now let’s see how we can do API testing in practice. First, you will need to select your approach.
 

For API testing in particular, having decent levels of coding expertise is necessary to build and write API test scripts. However, if your team only has basic scripting knowledge, it is recommended to go with codeless testing tools to achieve your goals faster and easier.
 

Let’s perform a mock API test on https://reques.in, which is a hosted REST API that’s ready to respond to your requests.
 

In this case, we will make a GET request to list the users. As you can see, we have the Base url as “https://reqres.in/api/users” and the “?page=2” as the query parameter.

  
 

Let’s see how it can be done in Katalon. To get started, first download and install the tool.


 

Download Katalon and See its Power in Action   

 

As you arrive at the Katalon Studio interface, navigate to File > New > Web Service Request. You can also create a test case, test suite, test suite collection, or write a new Groovy script here.   
 

  
 

Here we’ll name it “API sample test cases on Reqres”. The request type is “RESTful”, and our endpoint URL is https://reqres.in/api/users?page=2. Add any description if needed, and click OK.

 

 

You now have your API request ready to go! The screen below now shows the HTTP Method and the Endpoint URL, with the query parameters automatically parsed. You can now click on the Run button to execute the test.   
 

 

You can immediately see the response with a status of 200 OK and all of the user data listed below. You have successfully run a “manual” API test in Katalon with just a few clicks.

 

Of course, we don’t want to have to do this again and again, so we want to have a system of automated API tests ready to be run at each development cycle. With Katalon TestOps you can sync test creation with test management activities. From there, you can plan, create new tests, execute, and view detailed reports on your test history.

  
 

You can also reuse test artifacts across different projects for minimal maintenance. Data-driven testing is made simple with multiple data sources (e.g., XLS, CSV) and databases supported. Instead of manually inputting API parameters, we can create custom fields that dynamically fetch the right type of data from a spreadsheet to run your tests. Watch this video to see how:

 

 

 

Katalon also supports BDD with Cucumber files and a native Gherkin editor. Katalon is also API-centric, supporting all types of REST, SOAP/1.1, and SOAP/1.2 requests. Your tests can be imported from Swagger, Postman, and WSDL.

 

 

Learn More About Katalon

 

or

 

Start Your Free Trial Now


 

API Testing Best Practices

  1. Combine both manual testing and automated testing. Understand the nature of each approach and use them strategically in your API testing project.
  2. Ensure that you have gone through the API documentation before the actual testing begins. Verify that you have all of the details about the API available.
  3. Consider edge cases to achieve higher test coverage. These can be as simple as including unsupported characters in the URL. Data-driven testing is a well-recommended practice for this.
  4. Include performance tests for your project if you have the bandwidth.