API Testing

needle, threads, sewing thread

API – Application Programming Interface. An API is a way for two or more computer programs to communicate with each other. It bypasses a user interface and communication happens directly by making calls to its API. An API call is a simple process of sending a request to post or receive the information.

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 the 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.

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.

Image Source: https://martinfowler.com

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.

API Acceptance Criteria

Here is the list of a few of the acceptance criteria for different request types however, the list can be expanded based on the requirement and need.

Request TypeAcceptance Criteria
POSTCharacter limit validationMandatory fields validation
Creating a record just with mandatory fields
Creating a record with all the fields
Mapping entities with other entities
GETValidating the properties in response
Using filters (e.g. id, expand)
Verifying records with valid/invalid externals id’s
DELETEDeleting the record
Un-mapping entities with other entities
PUTUpdating all the values of the records
PATCHUpdating any key value of the record

The complete playlist of the API Testing gives you basic setup knowledge to advance usage of the tool.