Skip to main content

API Testing

API stands for Application Programming Interface. It is a set of protocols, routines, and tools for building software applications. APIs enable software components to communicate and interact with each other, allowing developers to integrate different functionalities into their applications.

APIs act as a layer between different software components, allowing them to exchange information in a standardized way. This allows developers to create applications that can interact with other applications or services, such as social media platforms, online payment gateways, and weather services, among others.

APIs can be public, allowing any developer to use them, or private, only accessible to authorized users. They can also be categorized based on the type of data they exchange, such as REST (Representational State Transfer) APIs, SOAP (Simple Object Access Protocol) APIs, and GraphQL APIs.

What is API Testing?

API testing is a type of software testing that focuses on testing the Application Programming Interfaces (APIs) of a software system. The purpose of API testing is to verify the functionality, reliability, performance, and security of the APIs that make up the software system.

API testing involves testing the request and response data of the APIs, as well as their behavior under different conditions, such as varying input data, load, and stress. API testing can be performed manually or using automated testing tools that can simulate API requests and validate their responses.

API testing is important because APIs are often the building blocks of complex software systems, and any issues or bugs in the APIs can have a cascading effect on the entire system. By testing the APIs thoroughly, developers can ensure that they are working as intended and that they can be integrated into other software components without issues. Additionally, API testing can help identify potential security vulnerabilities in the APIs, which can be critical for systems that handle sensitive data or transactions.

Why is API Testing Important?

API testing aims to verify programming interfaces' functionality, reliability, efficiency, and security.

Instead of standard user inputs (keyboard) and outputs in API testing, you use software to make calls to the API, receive the result, and save the system response.

In order to find bugs as early as possible, a developer needs to know immediately that their code changes have broken the build and need to be fixed.

The development lifecycle of test-driven processes requires that a large percentage of test sets run quickly and frequently.

Where does API testing fall in the Test Pyramid?

Test Pyramid is divided into 3 layers and it starts from Unit Tests, goes up to Service Tests and then UI tests.

Level 1: Unit Tests

Unit tests form the base of the test automation pyramid. You need to test each component or feature to ensure that they work as expected under isolated conditions, and this unit test execution is faster compared to other levels. It's important to do a lot of scenarios in unit testing - happy ways, error handling, etc.

Level 2: Service Tests or Integration Tests

Unit testing examines small pieces of code. However, service or integration tests should be run to test how this code interacts with other codes (which make up the entire software). In fact, they are tests that validate the interaction of a piece of code with external objects. These components can range from databases to external services (APIs).

Level 3: UI Tests or End-to-End Tests

The top level of the testing pyramid is UI or end-to-end testing. These ensure that all applications work as expected. End-to-end testing does exactly what the name implies: test that the application works flawlessly from start to finish.

Before you take a deep dive into API Testing, let's quickly look into some of the important terminologies used in API.

HTTP & HTTPS

HTTP is an acronym for Hypertext Transfer Protocol. HTTP allows different communication systems to communicate with each other.

HTTPS is an acronym for Hypertext Transfer Protocol Secure. The HTTP protocol does not provide the security of the data, while HTTP ensures the security of the data.

HTTP Request & Response

Communication between the client and server is done in the form of HTTP requests and responses. Take an example of a booking where you will be providing all the booking details such as first name, last name, total price and booking dates. As soon as the server receives the request it process and gives back the response confirming whether the request was successful or failed due to any reason.

HTTP Request contains the series of HTTP headers, header fields and message body. Which will send a request to the server.

curl -X POST \
https://restful-booker.herokuapp.com/booking \
-H 'Content-Type: application/json' \
-d '{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"bookingdates" : {
"checkin" : "2018-01-01",
"checkout" : "2019-01-01"
},
"additionalneeds" : "Breakfast"
}'

Above is an example of a POST request with the header and body like Content-Type

HTTP Response contains a Status line, a series of headers, and a response body. Once the request is completed the server gives a response.

HTTP/1.1 200 OK

{
"bookingid": 1,
"booking": {
"firstname": "Jim",
"lastname": "Brown",
"totalprice": 111,
"depositpaid": true,
"bookingdates": {
"checkin": "2018-01-01",
"checkout": "2019-01-01"
},
"additionalneeds": "Breakfast"
}
}

Above is an example of the response with the header, status code, and body.

JSON & XML

JSON and XML both are used to receive data from the server.

JSON

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data interchange format
  • JSON is plain text written in JavaScript object notation
  • JSON is used to send data between computers
  • JSON is language independent

JSON Example

{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

XML

  • XML stands for eXtensible Markup Language
  • XML is a markup language much like HTML
  • XML was designed to store and transport data
  • XML was designed to be self-descriptive
  • XML is a W3C Recommendation

XML Example

<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

HTTP Methods

Commonly-used HTTP methods are POST, GET, PUT, PATCH, and DELETE. These methods correspond to create, read, update, and delete (or CRUD) operations, respectively.

POST: Post request is used to send data to the server (e.g. Create a booking on a website)

GET: Get request is used to retrieve the data from the server (e.g. Retrieve the booking details from a website)

PUT: Replace all the content for a resource (e.g. Update all the booking details on a website)

PATCH: Partial update of the content for a resource (e.g. Update partial details or minor details on a website)

DELETE: Delete the resource (e.g. Delete the booking details from the website)

CRUD - Create, Read, Update and Delete

CRUD operation is done using HTTP methods.

CREATE: Create the resource (e.g. Create a user)

READ: Read the resource (e.g. Read the created user or existing user)

UPDATE: Update the resource (e.g. Update the user details)

DELETE: Delete the resource (e.g. Delete the user)

What are the most common types of API authentication?

Basic Auth

Basic authentication is probably the simplest form of API authentication. To authenticate with basic authentication, you must pass a username and password set to the API. To submit a username and password, add an "Authorization" header to your request.

Bearer Authentication

Bearer authentication, also known as token authentication, is a two-step process. In this model, as a user of the API, you must first obtain a token, which is then used to authenticate and approve your requests.

API Keys

Authentication with an API key is very similar to bearer authentication, the only difference is how the API key is obtained. Unlike tokens, API keys do not have an expiration date. Additionally, the API provider will generate an API key for you.

JSON Web Token (JWT)

Similar to bearer tokens, the authentication server issues JWT tokens after the user successfully login. JWT tokens are widely used because of their open standard (RFC 7519). Therefore, there are many open-source projects that use JWT tokens. Also, JWT tokens are self-contained, meaning that the token has claims.

HTTP response status codes

HTTP response status codes indicate whether a particular HTTP request completed successfully. Responses are grouped into five classes:

  • Informational responses (100 – 199)
  • Successful responses (200 – 299)
  • Redirection messages (300 – 399)
  • Client error responses (400 – 499)
  • Server error responses (500 – 599)

Common response status codes which you will see while working on APIs:

  • 200 OK: The request is OK.
  • 201 Created: The request is complete, and a new resource is created.
  • 204 No Content: A status code and a header are given in the response, but there is no entity-body in the reply.
  • 301 Moved Permanently: The requested page has moved to a new URL.
  • 400 Bad Request: The server did not understand the request.
  • 401 Unauthorized: The requested page needs a username and a password.
  • 402 Payment Required: You can not use this code yet.
  • 403 Forbidden: Access is forbidden to the requested page.
  • 404 Not Found: The server can not find the requested page.
  • 500 Internal Server Error: The request was not completed. The server met an unexpected condition.
  • 501 Not Implemented: The request was not completed. The server did not support the functionality required.
  • 502 Bad Gateway: The request was not completed. The server received an invalid response from the upstream server.
  • 503 Service Unavailable: The request was not completed. The server is temporarily overloading or down.
  • 504 Gateway Timeout: The gateway has timed out.
  • 505 HTTP Version Not Supported: The server does not support the "http protocol" version.

API Test Cases

API test cases are specific scenarios or test scripts that are designed to verify the functionality, reliability, performance, and security of the APIs being tested. Here are some common types of API test cases:

Positive Test Cases : These test cases verify the functionality of the API when correct input is provided. For example, if an API accepts a parameter that specifies a date, a positive test case would provide a valid date as input to verify that the API can handle it correctly.

Negative Test Cases : These test cases verify the behavior of the API when incorrect or invalid input is provided. For example, a negative test case for an API that accepts an email address as input would provide an invalid email address to verify that the API handles it correctly.

Boundary Test Cases : These test cases verify the behavior of the API at the boundaries of its input parameters. For example, a boundary test case for an API that accepts a range of values would provide the minimum and maximum values as input to verify that the API handles them correctly.

Load Test Cases : These test cases verify the performance of the API under varying loads. For example, a load test case would simulate multiple users making API requests simultaneously to verify that the API can handle the load without issues.

Security Test Cases : These test cases verify the security of the API by testing for vulnerabilities such as injection attacks, authentication issues, and data privacy breaches.

Error Handling Test Cases : These test cases verify that the API returns appropriate error messages and status codes when errors occur.

Integration Test Cases : These test cases verify the interaction between different APIs and services, ensuring that they can work together without issues.

These are just a few examples of the types of API test cases that can be used to thoroughly test the functionality, reliability, performance, and security of an API.