Skip to content

How To Do API Testing | Best Practices (2024)

API Testing

What is API Testing?

API testing is a type of testing that is used to evaluate that the API functions as expected. Quality assurance professionals analyse and test the APIs and evaluate whether APIs meet the expectations or not and are secure, robust and reliable.

Why API testing is important?

API is an integral part of any application. It’s the “middleman” of the layers and systems within an application or software. API testing is important as it ensures a reliable, safe, and secure connection between platforms. API testing enables us to find bugs at an early stage hence it is cost-effective.

We can perform API testing within the application before GUI testing, core functionality can be tested to expose small errors so productivity is improved. Through API testing, we can also check for vulnerabilities by using a specific set of parameters to simulate various phishing attack techniques.

The Importance of API Testing

API testing ensures several benefits to a product. Some of them are listed below:

  1. API testing helps in identifying the problems at the integration phase to make sure that two different systems interact together correctly.
  2. API testing uncovers the performance bottlenecks like high response time.
  3. API testing ensures that the desired operation is performed and API delivers the intended response.
  4. API testing helps in detecting and mitigating security issues such as SQL injection and cross-site scripting. This helps to ensure that the API is safe from common risks and that sensitive data is secure.
  5. API testing saves time and cost as it helps in detecting and fixing bugs at an early stage.

What should you test in an API | API testing Checklist

When we talk about API testing the first thing that comes to our mind is to validate the response codes and response body, but API testing is much more than that. Let’s try to decode what points should be considered while performing API testing.

1)HTTP status code verification

This is the most familiar test case while performing API testing. Validate that the API is returning the correct status code. Some common response codes are:

2xx (Success)

200: The Request has succeeded(GET/POST/HEAD).

201: The request has been fulfilled(POST/PUT).

204: The server successfully processed the request, but is not returning any content(DELETE).

3XX (Redirection)

301: Move permanently(GET/HEAD).

4XX(Client error)

400: Bad Request(Domain validation errors, missing data).

401: Invalid authentication token.

404: Not found(Does not exist or due to security reasons the service wants to mask).

429: Too many requests(Rate limiting)

5XX(Server errors)

500: Internal server error(General catch mechanism when server throws an exception).

503: Service unavailable(Server overloaded or down for maintenance).

2)Payload Verification

After verifying the status codes next step is to verify the response Payload. First, validate that the response body is not null or empty which is a pretty basic test case. The response body can be JSON or XML. Next, we need to validate the important keys in the response body. For example, if we are hitting an API to create a new user then a unique user ID must be returned in the response body.

Refer to Sample JSON Response.

{
    "firstName": "John",
    "lastName" : "Doe", 
    "age": 35,
    "userID" : 1001,
    "eMail" : "john@gmail.com"
}

Refer to sample Test cases for the above JSON payload.

TC_1: Response body is not empty
TC_2: Verify Response body contains userID
TC_3: userID is not null or blank
TC_4: Verify Unique User Id is created every time.
TC_5: Verify New user can not be created with same eMail. Email should be unique.

3)Validate Response Headers

The API gateway checks header values for threatening content. Headers hold additional information about the response. For example, the content-type header tells the browser what type of content the body contains. If the content-type header is blank or missing then the browser attempts to display the source most appropriately. This can cause a security threat.

The content-length header tells the size of the response body. Checking this field may reveal wrong or missing content.

TC_6:Validate that Content-Type header exist in the response headers, and its value should match the expected content type (e.g., "application/json", "application/xml", "text/html", etc.
TC_7: Verify the reposne type. i.e if content-type = JSON then response should be JSON.

4)Schema Validation

One of the important tests that we often tend to ignore is schema validation. Schema validation ensures that the response format is the same as the expected one. Validations rules can be like that data is in the key/value pair. The key should be in double quotes and must be a string, the response includes arrays and objects. If the schema is of object type then if we send a non-object request we should get an error. Similarly, we can specify min items and max items validation on the schema. JSON schema validation can be done using Tiny validator in Postman or using any javascript library.

Refer to the below schema for the JSON Payload

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    },
    "userID": {
      "type": "integer"
    },
    "eMail": {
      "type": "string"
    }
  },
  "required": [
    "firstName",
    "age",
    "userID",
    "eMail"
  ]
}

We can validate this schema by following the below test cases.

  1. Verify that the “first name” field exists and has a value of type string.
  2. Verify that the “lastName” field exists and has a value of type string.
  3. Verify that the “age” field exists and has a value of type integer.
  4. Verify that the “userID” field exists and has a value of type integer.
  5. Verify that the “Email” field exists and has a value of type integer.
  6. Verify the length constraints of each field. For Example, UserId should be of a minimum of 4 numbers.
  7. Verify that all fields are mandatory except the last name.

5)Authorization

Another test is to validate the authentication type. Multiple types of authentication are available such as basic auth, API key, Bearer token, and OAuth for security purposes. A few things can be validated for authorization like auth token expiration is set or if ‘Bearer’ needs to be appended with the token but still token is still working without it. Ensure API refuses all unauthorized calls.

6)Performance testing

It is considered a good approach to perform the basic level of performance testing for API. We can check the response load time, and response size using Postman. In automation testing, custom methods can be written to perform these kinds of validations. For example, we can validate that the execution time is less than 200ms.

pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});

7) AAA Rule (Arrange, Act, Assert)

The famous AAA pattern of testing is to arrange all necessary preconditions and input, act on the test, and assert the expected result. Without good assertions and tests, it is impossible to have full confidence in API behaviour. Assertions are checked every time a test runs.

API Testing using Assertions in Postman
Assertions

8)Negative TestCases

Negative testing is as important in API testing as in UI testing. For Example, attempt to create a resource with a name that already exists, or try to delete a resource that does not exist. Try to delete the user configuration without permission.

Attempt executing API with an expired token or try to use an unsupported method.

TC_01: Validate that if firstName is not provided then API should fail.
TC_02: Validate that if same email id is provided then API should fail with error code 500.

9)Destructive testing

This technique is used to intentionally fail the API to check the robustness and identify points of failure. For example intentionally send malformed request payload, overflow parameter values ex: if the title length is of 50 characters make it 100, and send empty payloads.

10)Integration Testing

As the API layer is the intermediate layer between the presentation layer and the internal layer, ensure that integration between third-party or internal services works properly. For example, an API can read or write some data in a database or any content management system then it should work properly to and fro.

API Testing Tools

Many tools are available in the market for API testing including paid tools. Some of the commonly used tools are mentioned below:

  • Postman
  • SoapUI
  • Apigee
  • Insomnia
  • Katalon Studio

Some tools are available to write test scripts like Rest Assured, rest sharp and super test. It depends on the requirement of which tool is a good fit. Ready-made tools like Postman are easy to use whereas writing your scripts gives you more freedom and flexibility.

How to start with API testing

To proceed with API testing some important points to keep in mind.

  1. Understand the requirements in detail. Go through the required documentation and understand the API’s purpose.
  2. The next step is to identify the target audience.
  3. Set up the test environment, and set the priorities.
  4. Define the input parameters.
  5. Create detailed test cases including both positive and negative scenarios.
  6. Carefully analyse the API testing tool considering the project requirements.
  7. Execute the tests and prepare detailed reports with pass, fail, skip, and blocked test cases.

Click here to learn API testing with Postman.