Search This Blog

Monday, April 5, 2021

API testing interview questions

An introduction to REST APIs
API stands for Application Programming Interface. Browser can offer some APIs, in the form of functions available to us. API also means another thing: creating a service that exposes some specific functionality, provided through a server that can be accessed by multiple clients.

Endpoints
  • In a REST API, we create a number of endpoints that a client can access.
  • Say we want to expose a list of people. We can create an endpoint that will respond to the /people route.
  • If our service listens on the domain test.com, we’d have the test.com/people URL.
  • This endpoint will provide data in any format, but generally we use JSON, a handy text-based format used to communicate data between two services.
  • This /people endpoint can provide a list of names of people, and an id for each person. This might be the id that we use to store them in the database, for example.
  • Our system can also expose another endpoint, which we can call /person. This accepts an id that uniquely identifies a person, like this: /person/1
  • Our API will provide more information about that person, for example age, email, address.
  • The important thing to note is that in the first endpoint we didn’t have any parameter, but this time we have one.
  • Parameters can be sent in different ways, and not all the endpoints will be used to send information from the server
Methods
  • We mentioned that the /people endpoint will return the list of people in our system.
  • This was a simplification, and it’s time to dig deeper.
  • A REST API uses the HTTP protocol principles to provide different functionality based on the HTTP method used: GET, POST, PUT, DELETE.
  • GET is the most common one. When a client calls our API endpoint with a GET method, it signals that it wants to read data.
  • GET /people will return a list of people.
  • GET /person/1 will return a person details.
  • When the HTTP method is POST, the meaning is completely different. The endpoint will be the same, but the action required will be another one.
  • For example we might create a POST /person endpoint that when called creates a new person in the database.
  • It receives data from the client, in a predefined format that we can choose. We’ll soon see an example made using Express.
  • GET and POST are the main 2 verbs used.
  • Sometimes we use PUT and DELETE: PUT is sometimes used to update a resource, like changing the address of a person. DELETE is used to remove a resource. Other times, POST is used for everything that is not reading, where GET is used
Naming API endpoints
  • Look how I used /people and /person above.
  • Those are nouns.
  • Using nouns for endpoints, and using HTTP methods for signaling the action, is considered a best practice.
  • Updating a person uses a POST request to the /person endpoint.
  • If you want to create an API to send a message to a person, you’d make a POST request using a /message endpoint, passing data to it to identify the person and the message you want to send.
A REST API is stateless
  • A REST API is stateless.
  • This means it does not have any memory between different requests.
  • Most APIs you can find implement an API Key mechanism that serves as a way to track who is calling an API, and provide a way to monitor usage and force limits.
  • An API can also be protected using a login/password mechanism. In this case an API authentication process will need to take into consideration an handshaking process that provides a token that then needs to be sent in every future request, to identify the user and the correct authorization.
Responses
  • An API call will return a response to the user, in 2 forms: an HTTP response status code, and an HTTP response body.
  • Every HTTP request has a status code.
  • We have some conventions regarding the HTTP response status code: when you use the browser to open a web page, the page will return a 200 OK status code. If the page is not found, a 404 NOT FOUND status code.
Common ones are:
  • 200 OK: this is the standard response for successful HTTP requests.
  • 201 Created: Typically a response to a POST request. The request has been completed, and a new resource has been created.
  • 400 Bad Request Due to a request error that was generated on the client, the server cannot process the request. Errors can include a malformed request, size too large to be handled, or others
  • 401 Unauthorized Sent when authentication is required and the client is not authorized
  • 403 Forbidden The resource is not available for various reasons. If the reason is authentication, prefer the 401 Unauthorized status code.
  • 404 Not Found The requested resource could not be found.
  • 405 Method Not Allowed The resource is not available through that HTTP method, but might be with another.
  • 500 Internal Server Error A generic server error message, given when an unexpected condition was encountered and no more specific message is suitable.
Note is that when you create an API you should always return the correct status code, to inform your clients. The response body is usually a JSON response with the data that was requested, or an error message.

What is API testing?
  • API (Application Programming Interface) specifies how some software components should interact with other, in other words it’s a set of functions and procedures that allows the creation of applications which access the features or data of an application or operating system.   Testing of these functions is known as API testing.
  • APIs are software protocols and tools that help clients and servers to communicate


What are access-tokens?
Access tokens are used in token-based authentication to allow an application to access an API. The application receives an access token after a user successfully authenticates and authorizes access, then passes the access token as a credential when it calls the target API. The passed token informs the API that the bearer of the token has been authorized to access the API and perform specific actions specified by the scope that was granted during authorization.

Common tests on APIs:
Some of the common tests we perform on APIs are as follows.
  • To verify whether the return value is based on the input condition. The response of the APIs should be verified based on the request.
  • To verify whether the system is authenticating the outcome when the API is updating any data structure
  • To verify whether the API triggers some other event or request another API
  • To verify the behavior of the API when there is no return value

Advantages of API Testing:
  • API Testing is time effective when compared to GUI Testing. API test automation requires less code so it can provide faster and better test coverage.
  • API Testing helps us to reduce the testing cost. With API Testing we can find minor bugs before the GUI Testing. These minor bugs will become bigger during GUI Testing. So finding those bugs in the API Testing will be cost-effective to the Company.
  • API Testing is language independent.
  • API Testing is quite helpful in testing Core Functionality. We can test the APIs without a user interface. In GUI Testing, we need to wait until the application is available to test the core functionalities.
  • API Testing helps us to reduce the risks.
What exactly needs to be verified in API Testing?
Basically, on API Testing, we send a request to the API with the known data and we analyze the response.
  • Data accuracy
  • HTTP status codes
  • Response time
  • Error codes in case API return any errors
  • Authorization checks
  • Non-functional testing such as performance testing, security testing

What are cookies?
  • Cookies are strings of data that a web server sends to the browser. When a browser sends a future request to the web server, it sends the same string to the web server along with its request.
  • Websites typically use cookies to ensure that users are recognized when they move between pages, so they don't get asked to log in again every time. Websites also use cookies to remember information users have entered. For example, e-commerce sites use cookies to remember the items placed in a shopping cart.

What are the tools used for API testing?

The tools used for various API testing are
  • SoapUI Pro
  • LoadUI Pro
  • Alertsite API monitoring
What must be checked when performing API testing?
During the API testing process, a request is raised to the API with the known data. This way you can analyze the validation response. While testing an API, you should consider:
  • Accuracy of data
  • Schema validation
  • HTTP status codes
  • Data type, validations, order and completeness
  • Authorization checks
  • Implementation of response timeout
  • Error codes in case API returns, and
  • Non-functional testing like performance and security testing
What is the best approach method to perform API testing?
The following factors should be considered when performing API testing:
  • Defining the correct input parameters
  • Verifying the calls of the mixture of two or more added value parameters
  • Defining the basic functionality and scope of the API program
  • Writing appropriate API test cases and making use of testing techniques such as equivalence class, boundary value, etc. to check the operability
  • Testing case execution
  • Comparing the test result with the expected result
  • Verifying the API behavior under conditions such as connection to files and so on.

What are the common tests performed on API’s?

The common tests performed on API’s

  • Verification of the API whether it is updating any data structure
  • Verify if the API does not return anything
  • Based on input conditions, returned values from the API’s are checked
  • Verification of the API whether it triggers some other event or calls another API

Mention the key difference between UI level testing and API testing?

UI ( User Interface) refers to testing graphical interface such as how user interacts with the applications, testing application elements like fonts, images, layouts etc. UI testing basically focuses on look and feel of an application.

While, API enables communication between two separate software systems. A software system implementing an API contains functions or sub-routines that can be executed by another software system

 What are major challenges faced in API testing?
If you can overcome the challenges in API Testing, you can be confident in the API testing interview too. They are:

  • Parameter Selection
  • Parameter Combination
  • Call sequencing
  • Output verification and validation
  • Another important challenge is providing input values, which is very difficult as GUI is not available in this case.
What kinds of bugs that API testing would often find?
  1. Missing or duplicate functionality
  2. Fails to handle error conditions gracefully
  3. Stress
  4. Reliability
  5. Security
  6. Unused flags
  7. Not implemented errors
  8. Inconsistent error handling
  9. Performance
  10. Multi-threading issues
  11. Improper errors

Explain what is SOAP?

SOAP-stands for Simple Object Access Control, and it is an XML based protocol for exchanging information between computers.


Explain what is REST API?

It is a set of functions to which the developers performs requests and receive responses. In REST API interaction is made via HTTP protocol

REST – stands for Representational State Transfer, it is quickly becoming defacto standard for API creation.

API Testing Types?
API testing typically involves the following practices:
  • Unit testing: To test the functionality of individual operation
  • Functional testing: To test the functionality of broader scenarios by using a block of unit test results tested together
  • Load testing: To test the functionality and performance under load
  • Runtime/Error Detection: To monitor an application to identify problems such as exceptions and resource leaks
  • Security testing: To ensure that the implementation of the API is secure from external threats
  • UI testing: It is performed as part of end-to-end integration tests to make sure every aspect of the user interface functions as expected
  • Interoperability and WS Compliance testing: Interoperability and WS Compliance Testing is a type of testing that applies to SOAP APIs. Interoperability between SOAP APIs is checked by ensuring conformance to the Web Services Interoperability profiles. WS-* compliance is tested to ensure standards such as WS-Addressing, WS-Discovery, WS-Federation, WS-Policy, WS-Security, and WS-Trust are properly implemented and utilized
  • Penetration testing: To find vulnerabilities of an application from attackers
  • Fuzz testing: To test the API by forcibly input into the system in order to attempt a forced crash



How to test API’s ?

To test the API’s you should follow the following steps

  • Select the suite in which you want to add the API test case
  • Choose test development mode
  • Develop test cases for the desired API methods
  • Configure application control parameters
  • Configure test conditions
  • Configure method validation
  • Execute API test
  • View test reports
  • Filter API test cases
  • Sequence API test cases

Mention what the main areas to be taken in consideration while writing API document ?

The key area to be considered when writing API documents are

Source of the content
Document plan or sketch
Delivery layout
Information required for each function in the document
Automatic document creation programs

In API document explain how to document each function ?What are the tools used for documentation?
  • Description: Small description about what a function does
  • Syntax: Syntax about the parameter of the code, the sequence in which they occur, required and optional elements etc.
  • Parameters: Functions parameters
  • Error Messages: Syntax of error messages
  • Example Code: Small snippet of code
  • Related Links: Related functions
What is API Authentication?
  • Authentication is when an entity verifies the identity of a user. n other words, it proves that the clients trying to access a remote server are really who they say they are.
  • Authorization is the next thing that happens after successful authentication. It is the approval that a certain client has the right to make a request. Simply, authorization is when an entity verifies that you have the right to access data or information on a given server.
  • Since API is a profound entity with an external resource that has the capability of accepting and responding to protected resource requests by users and clients, they must be equipped to ensure that applications and clients trying to access data are authentic, so that they can proceed to authorized full access when identity is confirmed. The processes of certifying the identity of users trying to access resources on the server and this is what is known as API authentication.

Explain API framework?
API framework is self-explanatory. Values for test run and for holding the configurable parts, config file is used.  Automated test cases must represent in “ parse-table” format within config file.  When testing API, it is not necessary to test each API so the config file have some section whose all API are activated for that specific run.

How does the API Builder work?

API Builder is a PLSQL program consists of four SQL files
  • For setting API parameters and starting the process one file is responsible
  • Two files are created for temporary tables and Master package to create the outputted code
  • Fourth file creates “spooled” output of the code into a file called “output_script_.sql”
What to test with an API?
The different categories of tests are: 
Security testing checks how well the API is protected from malicious actors. It ensures that resources (data) are protected and only provided to authenticated or authorized clients.

Functional testing checks whether the endpoints are satisfying their requirements. Functional and security testing have more options when it comes to testing. Some of the things that are tested include:
  • HTTP status code (i.e 200, 404, 405)
  • data
  • headers
Performance testing makes sure that an API can respond to requests of specific sizes, or can respond to clients quickly enough to satisfy system requirements. Performance testing may time how long it takes for a request to receive a response.

Connectivity determines if the API is responding and operational. If you are focusing on the connectivity of an API, you may execute a simple “ping” test to make sure that the server is responding.

Which are the most Common Methods of API Authentication?
Although there are several methods of API authentication, here are some of the most popular:
  • HTTP Basic Authentication
  • API Key Authentication
  • OAuth Authentication
HTTP Basic Authentication
HTTP Basic Authentication is the simplest form of identification. This technique combines username and password to form a single value and passes it through a special HTTP header known as authorization where they are encoded with Base64. Therefore, when a client makes a request, the server checks the Authorization header and compares it to the credentials (username and password) it has stored. If they match, the server fulfills the client request, and if not, a special status code is sent back to inform clients that authentication has failed and their request denied.

API Key Authentication
API Key authentication is a technique that was invented to overcome the weaknesses of shared credentials which was a big problem in HTTP Basic authentication. The API key is usually a long series of numbers and letters that you either include in the request header or request URL. When the client authenticates the API key, the server stamps their identity and allows them to access data. API vendors might provide you with a public and private key depending on your needs, where the former can be used to limit users to certain functions, and the latter acts like a password that allows you full access.

Although this scheme is highly reliable, there some few tips that can make the API more secure:
  1. Make sure that you use HTTPS at all times.
  2. Keep it simple
  3. Avoid exposing information on URLs
  4. Use password hash
  5. Install some parameter validation

OAuth Authentication
Technically, Oauth is a technique that does both authentication and authorization. It is a form of API authentication that gives applications with the ability to communicate with API server to provide access. When a user logs into the system, it requests authentication in the form of a token. The client is required to forward the request to an authentication server, which either allows or rejects this it. OAuth authentication is fundamentally a more secure and powerful system than the rests, and it’s quickly becoming the number one choice for many clients and applications.

Explain API Security Best Practices?
A data breach leads to compromised information and a loss of trust from customers. A DDoS attack will disrupt an organization’s ability to function.

1. Assess the Data Value
The level of security necessary depends on the value of the data. APIs created for entertainment purposes do not require the same level of protection as client information. If an API is organizing information that is readily accessible on the web, there is little need for complex security solutions. However, if the API holds data such as a customer’s credit card information, it needs a high level of protection.

2. Examine API Vulnerabilities
People who want to steal information are constantly at work looking for ways to take advantage of vulnerabilities in the structure and design of an API. IT personnel must be informed about potential issues and recode the program accordingly. Some organizations employ a threat modeling process to look for vulnerabilities as well as potential attackers. Regular review will help developers find coding errors that might make the API subject to infiltration.

3. Encryption or Tokenization
  • Data encryption is a standard safety practice for sharing information online. Unless it is an open-source project, most APIs require the user to have an encryption key that protects data as it travels. At the user’s endpoint, the browser uses the key to decrypt information. If a hacker can access the key, he or she can decipher the data.
  • Tokenization is another API security strategy. This security technology began as an online payment safety solution. Unlike traditional encryption, data travels as a randomized placeholder or token with no direct relationship to the client. Even if a hacker intercepts the token, there is not a simple way to extract the information.
4. Using an API Gateway
 As APIs grow in popularity, third-party programmers are developing tools to make these databases more secure and functional. An API gateway is a layer of structure and protection between users and API data. For companies with limited IT resources, a third-party gateway has the advantage of handling several API features. In addition to providing web API security through encryption and authorization, the gateway can also assist with billing, request rate limits, and analytics.

5. Placing Limits on Requests
 REST API security involves more than protecting data. Cybercriminals can also cause problems by disrupting the API. To communicate with an API, an application makes a GET request to receive information or a POST request to add information. With no limits on access, a cybercriminal can carry out a nuisance attack by flooding an API with requests. If the database is trying to process thousands of requests from a single application, it will not be able to provide data to other users. Requests from valid users will time out and fail.

6. Establishing Authorization Levels
 Unless the API is a fully open-source project, it is important to create access limits. In a typical arrangement, basic users can only retrieve data from the database and cannot modify information. The next level of access may allow a user to add information such as new accounts. It may require another authorization level to change entries in the API. Finally, an IT professional will have full access to modify the underlying code.

7. Data Validation
 An API stores and releases data according to rules established by the developer. If there are no clear rules in place, it damages the functionality of the database. Hackers can disrupt the API by posting large entries that take up extra storage space. Invalid entries can cause corrupted files that throw error messages. For data entry, validation will include making sure that an entry is not empty and is in the proper format.

8. Security Analytics
 While some cyberattacks are big and disruptive, others are subtle. If a cybercriminal is trying to steal information without the organization noticing, there may not be an obvious attack. API analytics is a helpful tool in REST API security. An organization can not only track the frequency of requests but also the location or origin of those requests. The IT professional responsible for a private API might set it up so that the system flags suspicious IP addresses or requires extra authentication.

CRUD – What is CRUD?
CRUD – again is:
Create
Read
Update
Delete

What are API Credentials?
API credentials can be defined as unique identifiers that must be added to code before you make a call via an API. Various APIs support different authorization credentials, but the typical APIs feature credentials options such as:
  • Name
  • API password
  • Auth token
  • API key
  • Status 
  • Actions
Name: This is the first credential that you’ll be given for primary use. You can add more names for use by your partners or affiliates. 

API password: This acts as your ID when you are requesting a token or when you want to make a call. It is automatically generated when you sign in, but you can create a new one using alphanumeric and no spaces.

Auth Token: For you to access private user data, you must send an Auth token along with the request. The app first sends a client ID, and possibly a secret word to obtain a token. Auth credentials can be generated for service accounts, web applications, or installed applications.  

API keys: If a request doesn’t provide a token, it must offer an API key. The key is used to identify the project that is making the call and offers API access, reports, and quota.  

Status: This credential denotes the membership level by defining whether it is active or inactive. 

Actions: This allows you to either edit or deletes API credentials. 

cURL – What is cURL?
  • Curl is object-oriented programing software that is used to transfer data through a vast array of Internet Protocols for a given URL. It is a command-line utility that permits the transfer of files within the URL syntax. Curl is basically a client-side program which boasts commands that are designed in a way that they work to check connectivity to the URLs and facilitate data transfer.
  • In the word cURL; ‘c’ stands for a client, while ‘URL’ indicates that curl works with URLs. This software supports various protocols including FTP, HTTPS, HTTPS, TELNET and SMT which makes it an ideal candidate for interacting with APIs.
  • Curl can work on any platform and on any hardware that exists today
When to use cURL?
Since curl supports connection to remote systems over HTTP, HTTPS, TELNET and a vast array of other protocols, it is used when a script wants to access information from a remote system just like it was a local file/data stream. This is critical for developers who would wish to acquire data from a remote system and present it as they had it locally. Curl can be used in a terminal or command prompt, but you need to ensure that it is installed in the system you are using before you try to use it.

cURL Examples
1. Return the HTTP Headers of a URL Only
Curl -I https:// www.keycdn.com/
The -I option is used to instruct Curl to only fetch the HTTP header form a particular page or resource.

2. Making HTTP GET Request
Curl https:// www.keycdn.com/
This shows a basic curl command calling a GET request for a website URL.

3. To Bestow an Additional HTTP Header
The curl command can also be used to add a new HTTP Header to GET requests. All you need s to add the – H option followed by the header name and value in enclosed quotes.

curl -H "X-Header: Value" https://www.keycdn.com/

4. Continue a Download
Curl command can also be used to resume a download that was purposely stopped or interrupted. You simply add the -c to the Curl command in question and the system will resume downloading an item from where it stopped.
curl -C - -O https://cdn.keycdn.com/img/cdn-stats.png

What is a payload in API?
A payload in API is the actual data pack that is sent with the GET method in HTTP. It is the crucial information that you submit to the server when you are making an API request. The payload can be sent or received in various formats, including JSON. Usually, the payload is denoted using the “{}” in a query string.

Payload = “{}”

Example of Payloads
The payload is used in the context of message protocol to differentiate between the assisting and actual data in a query string. For instance, Let’s consider this JSON web service response.
{
    "status": "OK",
    "data":
        {
            "message": "Welcome, world!"
        }
}
In the above example, the payload is the Welcome, World! Since it is the part of the query string that the user is interested in. The rest of the information is referred to as the overhead data. This is because it is only used to show the source or destination and display authenticity.

API Payload Formats
Basically, you’ll find three payload formats:
  • Request payload format
  • OK response payload format
  • FAILED response payload format
API Request Payload Format
This request must have two parameters and a sub element:
  • Interface Type
  • Method name
  • Parameters
Example:

{
  "interfaceType": "Manual",
  "methodName": "",
  "parameters": {
  }
}

API OK Response Payload Format
These features one parameter and one sub element:
  • Response type
  • Data. It may be zero or more parameters
Example:
{
  "responseType": "OK",
  "data": {
    "someName1": "value",
    "someName2": "value",
    "someName3": "value"
  }
}

API FAILED Response Payload Format
This also contains one parameter and one subelement:

  • Response type
  • Messages. May feature an array of zero or multiple error messages
Example:
{
  "responseType": "FAILED",
  "messages": [
    {
      "message": ""
    },
    {
      "message": ""
    },
    {
      "message": ""
    }
  ]
}


Explain what is TestApi ?
TestApi is a library of utility and test APIs that enables testers and developers to create testing tools and automated tests for .NET and Win32 application.  It provides a set of common test building blocks, types, data-structure and algorithms.

What is Input injection and what are different ways of doing it ?
Input Injection:  It is the act of simulating user input, in several ways you can simulate user input.
  • Direct Method Invocation
  • Invocation using an accessibility interface
  • Simulation using low-level input
  • Simulation using a device driver
  • Simulation using a robot

What are the main challenges of API testing?
The main challenges in API testing is
  1. Parameter Selection
  2. Parameter Combination
  3. Call sequencing
Other challenges with API Testing include:
  • Updating schemas. Applications evolve and the structure of data can change
  • Input parameters. Endpoints have the possibility to accept many combinations of values and data types. This can make it difficult to get the full test coverage that is desired.

What is API testing with runscope ?
Runscope is a web application that provides backend services and easy to use interface for testing APIs.

Explain what are the principles of API test design?

The principle for API test design are
  1. Setup : Create objects, start services, initialize data etc
  2. Execution: Steps to exercise API or scenario, also logging
  3. Verification: Oracles to evaluate execution outcome
  4. Reporting: Pass, failed or blocked
  5. Clean up: Pre-test state

What are the types of Bugs will API testing finds?

The types of Bugs, API will find
  • Missing or duplicate functionality
  • Fails to handle error conditions gracefully
  • Stress
  • Reliability
  • Security
  • Unused flags
  • Not implemented errors
  • Inconsistent error handling
  • Performance
  • Multi-threading issues
  • Improper errors/messaging
  • Security issues
  • Multi-threaded issues
API Testing Best Practices:
  • Test for the expected results
  • Add stress to the system by sending a series of API load tests
  • Group API test cases by test category
  • Create test cases with all possible inputs combinations for complete test coverage
  • Prioritize API function calls to make it easy to test
  • Create tests to handle unforeseen problems
  • Automate API testing wherever it is possible

What are the tools used for API test automation?

While testing Unit and API testing,  both target source code, if an API method is using code  based on .NET then the tool which is supporting should have .NET

Automation tools for API testing can be used are
  • NUnit for .NET
  • JUnit for Java
  • HP UFT
  • Soap UI
What are API Parameters?
API parameters are the variable parts of a resource. They determine the type of action you want to take on the resource. Each parameter has a name, value type ad optional description. Whenever you want to build a REST API, you have to decide which parameters should be present in the API endpoint. In simple terms, API parameters are options that can be passed with the endpoint to influence the response. 

Types of REST API Parameters
There are four different parts of parameters which are often documented in separate groups on the same page. They include:
  • Header parameters – These parameters are featured in the request header and are usually related to authorization.
  • Query parameters – These are separated from the hierarchy parameters by a question mark
  • Request body parameters – they are included in the request body and are used to send and receive data via the REST API.
  • Template/Path parameters – Set off within curly braces, path parameters are placed within the path of an endpoint just before the query string, and they provide developers with an effective way to parameterize resources.
  • Matrix parameters – They come in between the resource path and Query parameters and are separated from the hierarchy parameters by a semicolon.
  • Plain Parameters – These are parameters which are defined in a request and are easily accessible in ReadyAPI but are omitted when the request is submitted.

Mention the steps for testing API ?

API testing steps:
  1. Select the test case that has to be fulfilled
  2. For API call develop a test case
  3. To meet the test case configure the API parameters
  4. Determine how will you validate a successful test
  5. Using programming language like PHP or .NET execute the API call
  6. Allow the API call to return the data to validate

What are the common protocols that are testing in API testing ?
  • HTTP
  • JMS
  • REST
  • SOAP
  • UDDI
DOM – What is the DOM?
  • DOM stands for Document Object Model and refers to an interchange to web pages.
  • Programmers apply DOM to generate documents and establish their structure by adding or deleting content from the said document. The DOM interacts with different kinds of documents such as the XML and HTML documents.
  • Any element of substance or data found in HTML and XML documents can be approached, deleted or altered in any manner through the Document Object Model.

What is API Testing?

An API (Application Programming Interface) is a collection of software functions and procedures, called API calls, that can be executed by other software applications. Application developers code that links to existing APIs to make use of their functionality. This link is seamless and end-users of the application are generally unaware of using a separately developed API.
During testing, a test harness-an application that links the API and methodically exercises its functionality-is constructed to simulate the use of the API by end-user applications. The interesting problems for testers are:
1. Ensuring that the test harness varies parameters of the API calls in ways that verify functionality and expose failures. This includes assigning common parameter values as well as exploring boundary conditions.
2. Generating interesting parameter value combinations for calls with two or more parameters.
3. Determining the content under which an API call is made. This might include setting external environment conditions (files, peripheral devices, and so forth) and also internal stored data that affect the API.
4. Sequencing API calls to vary the order in which the functionality is exercised and to make the API produce useful results from successive calls.

 
What is meant by API Testing? Explain the API Testing process.
 API testing is to make sure that the basic units of the software application function perfectly well. Reason why we perform API testing right from the initial stages of the product cycle to the final phase, ensuring that the product release in the market is error-free and worth every penny you invested. API testing process involves testing the methods of NET, JAVA, J2EE APIs for any valid, invalid, and inopportune inputs, plus testing the APIs on Application servers.

During testing, a test harness-an application that links the API and methodically exercises its functionality-is constructed to simulate the use of the API by end-user applications. The interesting problems for testers are:

1. Ensuring that the test harness varies parameters of the API calls in ways that verify functionality and expose failures. This includes assigning common parameter values as well as exploring boundary conditions.     

 2. Generating interesting parameter value combinations for calls with two or more parameters.

3. Determining the content under which an API call is made. This might include setting external environment conditions (files, peripheral devices, and so forth) and also internal stored data that affect the API.

4. Sequencing API calls to vary the order in which the functionality is exercised and to make the API produce useful results from successive calls.

During testing, a test harness-an application that links the API and methodically exercises its functionality-is constructed to simulate the use of the API by end-user applications. The interesting problems for testers are:

1. Ensuring that the test harness varies parameters of the API calls in ways that verify functionality and expose failures. This includes assigning common parameter values as well as exploring boundary conditions.
2. Generating interesting parameter value combinations for calls with two or more parameters.

3. Determining the content under which an API call is made. This might include setting external environment conditions (files, peripheral devices, and so forth) and also internal stored data that affect the API.

4. Sequencing API calls to vary the order in which the functionality is exercised and to make the API produce useful results from successive calls.

How tester can do API testing by manually ,could u please explain it.

API testing is specifically the testing of API functions. One should design the test cases even before the completion of API functions. The process typically includes the following steps.
  1. Path testing. Path testing is to check each independent path that a code module could possibly execute. It indicates the low bound value of the test cases that should be written.
  2. Equivalence partitioning and boundary value analysis. Whenever a number is required as an input of a API function, one should be alert for the need of EP and BVA.
  3. Coverage testing. Coverage testing is operated on a more detailed level. There are several aspects of a API functions that requires the check of percentage of being cover. Statement coverage checks the percentage of statements in a API that are covered by test cases. Branch coverage is to make sure each predicate in a API is checked for both true and false condition. Condition coverage is to pass a predetermined input for every condition of every predicate in a API and check if it can get a predetermined output. For a very large code block, only 50% of condition coverage can be achieved.        

How do you test a backend API?

How you approach testing an API depends on a lot of things. Will the API be a public API that will be consumed by some external people/systems, or is it a part of a larger product’s infrastructure? API is a general term that is sometimes used to describe anything from a COM interface, to a DLL or JAR you can reference, to a REST web service. Different approaches can be applied to testing these different things.

Often, if the API is part of your infrastructure you can test it pretty thoroughly through unit testing and the use of the product that consumes it.

If it is an externally consumable API then you need to be much more thorough because people could use it in different ways than you might expect and send data in much different formats, etc. It also usually needs to make sense, be intuitive and be well documented if it is externally consumable. You would also need to be more cautious about what is private and public, which may not be as important for an API that is only used by a single product.

Testing an API nearly always requires you to create some sort of consumer for testing purposes. You have to create an application to interact with the API. The application is usually very simple and driven by automated test cases and not manual user interaction, although I have seen cases where people created a complex GUI app for testing purposes, and cases where the testing was still mostly manual through exercising that app.

If the API has dependencies, you may choose to mock those dependencies out so you can more thoroughly test all of those interactions and hit all of the positive and negative code paths. For instance, if the API interacts with a database and has the ability to create, modify and delete data you may want to mock the interaction with the database to more easily test cases such as deleting a record when it does not exist, or when it is the final record, or when it is unable to be deleted because of dependencies or even when the connection to the database is unavailable – you can then see how your API would handle these situations.

What is an API?
API stands for Application Programming Interface, which specifies how one component should interact with the other. It consists of a set of routines, protocols and tools for building the software applications.

What is an API Testing?
The API Testing is performed for the system, which has a collection of API that ought to be tested. During Testing, a test of following things is looked at.
  • Exploring boundary conditions and ensuring that the test harness varies parameters of the API calls in ways that verify functionality and expose failures.
  • Generating more value added parameter combinations to verify the calls with two or more parameters.
  • Verifying the behavior of the API which is considering the external environment conditions such as files, peripheral devices, and so forth.
  • Verifying the Sequence of API calls and check if the API’s produce useful results from successive calls.
Common Tests performed on API’s
  • Return Value based on input condition – The return value from the API’s are checked based on the input condition.
  • Verify if the API’s does not return anything.
  • Verify if the API triggers some other event or calls another API. The Events output should be tracked and verified.
  • Verify if the API is updating any data structure.
What is an API?
API is an acronym for Application Programming Interface.

It enables communication and data exchange between two separate software systems. A software system implementing an API contains functions/sub-routines which can be executed by another software system.

What is API testing?
API testing is entirely different from GUI testing and mainly concentrates on the business logic layer of the software architecture. This testing won’t concentrate on the look and feel of an application.

Instead of using standard user inputs(keyboard) and outputs, in API Testing, you use software to send calls to the API, get output, and note down the system’s response.

API Testing requires an application to interact with API. In order to test an API, you will need to

Difference API and Unit Testing?
API testing
API is owned by QA team
API is mostly black box testing
Full functionality of the system is considered in API testing as it will be used by the end-user (external developers who will use your API )
API test are often run after the build is ready and authors do not have access to the source code

UNIT testing
Unit testing is owned by development team
Unit testing is white box testing
Unit testing is done to verify whether each unit in isolation performs as expected or not
For each of their module the developers are expected to build unit tests for each of their code modules and have to ensure that each module pass unit test before the code is included in a build


Use Testing Tool to drive the API
Write your own code to test the API
The API Testing is performed for the system, which has a collection of API that ought to be tested. During Testing, a test of following things is looked at.

  • Exploring boundary conditions and ensuring that the test harness varies parameters of the API calls in ways that verify functionality and expose failures.
  • Generating more value added parameter combinations to verify the calls with two or more parameters.
  • Verifying the behavior of the API which is considering the external environment conditions such as files, peripheral devices, and so forth.
  • Verifying the Sequence of API calls and check if the API’s produce useful results from successive calls.

API testing is entirely different from GUI testing and mainly concentrates on the business logic layer of the software architecture. This testing won’t concentrate on the look and feel of an application.

Instead of using standard user inputs(keyboard) and outputs, in API Testing, you use software to send calls to the API, get output, and note down the system’s response.

API Testing requires an application to interact with API. In order to test an API, you will need to

How to Use CURL to Send API Requests
curl is a command-line utility that can be used to send requests to an API.
API requests are made up of four different parts:
  • The endpoint. This is the URL which we send requests to.
  • The HTTP method. The action we want to perform. The most common methods are GET POST PUT DELETE and PATCH
  • The headers. The headers which we want to send along with our request, e.g. authorization header.
  • The body. The data we want to send to the api.

curl Syntax
The syntax for the curl command is:
curl [options] [URL...]
The options we will cover in this post are:
-X or --request - HTTP method to be used
-i or --include - Include the response headers
-d or --data - The data to be sent to the API
-H or --header- Any additional headers to be sent

HTTP GET
The GET method is used to fetch a resource from a server. In curl, the GET method is the default method, so we don’t need to specify it.

Example: curl https://jsonplaceholder.typicode.com/posts

GET With Query Parameters
We can also send query parameters along with the curl GET request.

Example:  curl https://jsonplaceholder.typicode.com/posts?userId=5

HTTP POST
The POST method is used to create a resource on the server.
To send a curl POST request we use the option -X POST.

POST Form Data
Example:
curl -X POST -d "userId=5&title=Post Title&body=Post content." https://jsonplaceholder.typicode.com/posts

By default, curl uses Content-Type: application/x-www-form-urlencoded as the Content-Type header, so we don’t need to specify it when sending form data.

POST JSON
To POST a JSON by curl we have to specify the Content-Type as application/json.
Example:
curl -X POST -H "Content-Type: application/json" \
    -d '{"userId": 5, "title": "Post Title", "body": "Post content."}' \
    https://jsonplaceholder.typicode.com/posts


HTTP PUT
The PUT method is used to update or replace a resource on the server. It replaces all data of the specified resource with the supplied request data.
Note: For a PUT request, we have to provide all data in the request body.
To send a curl PUT request we use the option -X PUT.

Example:
curl -X PUT -H "Content-Type: application/json" \
    -d '{"userId": 5, "title": "New Post Title", "body": "New post content."}' \
    https://jsonplaceholder.typicode.com/posts/5


The above PUT request will replace our previously created post with “New post title” and “New post body”.

HTTP PATCH
The PATCH method is used to make partial updates to the resource on the server.
Note: For a PATCH request, we don't have to provide all data. We only send the data we want updated.
To send a curl PATCH request we use the option -X PATCH.

Example:
curl -X PATCH -H "Content-Type: application/json" \
    -d '{"userId": 5, "body": "Updated post content."}' \
    https://jsonplaceholder.typicode.com/posts/5

Notice how we are only sending the body with “Updated post content” as we are doing a partial update.

HTTP DELETE
The DELETE method is used to remove the specified resource from the server.
To send a curl DELETE request we use the option -X DELETE.
curl -X DELETE https://jsonplaceholder.typicode.com/posts/5

Note: The DELETE method has no body.

Authentication
Sometimes an API endpoint has restricted access and will only serve requests to authenticated and authorized users. For these requests, we have to provide an access token in the header of the request.
To send a curl header, we use: -H option.

The following request sends POST request with a bearer token in the header:

curl -X POST \
  https://some-web-url/api/v1/users \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer {ACCESS_TOKEN}' \
  -H 'cache-control: no-cache' \
  -d '{
  "username" : "myusername",
  "email" : "myusername@gmail.com",
  "password" : "Passw0rd123!"
}'


The full list of HTTP status codes 
The full list of HTTP status codes with a short description of the most common response codes.
When we do API testing, usually the first thing that we check on the response from an API call is the status code. It is essential that we are familiar with at least the most common status codes so we can identify issues quicker.
  • 1×× Informational
The 1xx (Informational) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response.
  • 100 Continue
  • 101 Switching Protocols
  • 102 Processing
  • 2×× Success
The 2xx (Successful) class of status code indicates that the client’s request was successfully received, understood, and accepted.
  • 200 OK
  • The 200 (OK) status code indicates that the request has succeeded. The payload sent in a 200 response depends on the request method.
  • 201 Created
  • The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created.
  • 204 No Content
  • The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
  • 202 - Accepted
  • 203 - Non-authoritative Information
  • 205 - Reset Content
  • 206 - Partial Content
  • 207 - Multi-Status
  • 208 - Already Reported
  • 226 - IM Used

3×× Redirection
The 3xx (Redirection) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
  • 301 Moved Permanently
  • The 301 (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.
  • 302 Found
  • The 302 (Found) status code indicates that the target resource resides temporarily under a different URI.
  • 304 - Not Modified
  • 300 - Multiple Choices
  • 303 - See Other
  • 305 - Use Proxy
  • 307 - Temporary Redirect
  • 308 - Permanent Redirect

4×× Client Error
The 4xx (Client Error) class of status code indicates that the client seems to have erred.
400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax).
  • 401 Unauthorized
  • The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
  • 403 Forbidden
  • The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it.
  • 404 Not Found
  • The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
  • 405 Method Not Allowed
  • The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource.
  • 415 Unsupported Media Type
  • The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource. The format problem might be due to the request’s indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.
  • 402 Payment Required
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Payload Too Large
  • 414 Request-URI Too Long
  • 416 Requested Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I’m a teapot
  • 421 Misdirected Request
  • 422 Unprocessable Entity
  • 423 Locked
  • 424 Failed Dependency
  • 426 Upgrade Required
  • 428 Precondition Required
  • 429 Too Many Requests
  • 431 Request Header Fields Too Large
  • 444 Connection Closed Without Response
  • 451 Unavailable For Legal Reasons
  • 499 Client Closed Request

5×× Server Error
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.
  • 500 Internal Server Error
  • The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
  • 502 Bad Gateway
  • The 502 (Bad Gateway) status code indicates that the server while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
  • 503 Service Unavailable
  • The 503 (Service Unavailable) status code indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.
  • 504 Gateway Timeout
  • The 504 (Gateway Timeout) status code indicates that the server while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
  • 501 Not Implemented
  • 505 HTTP Version Not Supported
  • 506 Variant Also Negotiates
  • 507 Insufficient Storage
  • 508 Loop Detected
  • 510 Not Extended
  • 511 Network Authentication Required
  • 599 Network Connect Timeout Error

What is HTTP?
  • HTTP stands for Hypertext Transfer Protocol.
  • It is a communications protocol and is used to send and receive web pages and files over the internet.
  • HTTP works by using a user agent (e.g. a browser) to connect to a server. The server must be located using a URL or URI. This always contains http:// at the start. It normally connects to port 80 on a computer.

What is HTTPS?
HTTPS stands for Hypertext Transfer Protocol Secure. This is a more secure version of HTTP and starts with https:// at the beginning of the URL. It encrypts all the information that is sent and received. This can stop malicious users such as hackers from stealing the information and is often used on payment websites. HTTPS uses port 443 for communication instead of port 80.

What is an HTTP Request?
HTTP stands for Hypertext Transfer Protocol and is a way of sending messages from one computer to another computer over the internet.

An HTTP request is sent to a specific URL and consists of a VERB, a set of HTTP Headers and a Body or Payload.

An example HTTP request is:
GET https://devqa.io/ HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/plain
Host: devqa.io
User-Agent: Apache-HttpClient/4.5.4 (Java/1.8.0_144)
Accept: text/html,application/xhtml+xml

URL
URL is a Uniform Resource Locator and is the address we use to access websites and web applications. URLs occur most commonly to reference web pages (http), but are also used for file transfer (ftp), email (mailto), and other applications.

Most web browsers display the URL of a web page above the page in an address bar. A typical URL could have the form https://devqa.io/index.html, which indicates a protocol http, a hostname devqa.io, and a file name index.html.


Request Verbs
Request VERB specifies the type of request e.g. GET, POST, PUT, DELETE.

A Web Browser will usually make GET requests and POST requests, whereas when working with HTTP APIs the typical HTTP Verbs used are: GET, POST, PUT, DELETE.

  • GET request, as the name suggests, asks for a resource or to read information from the server e.g. clicking on a link. GET requests are visible in the browser’s address bar.
  • POST request, on the other hand, supply information to the server e.g. submitting a login or registration form. To create an entity, we would use POST requests. Also, POST requests are not visible in the browser’s address bar.
  • PUT request is used to update information on the server. For example, an existing user wishes to update his password, then a PUT request is used.
  • DELETE request deletes information on the server.

Both POST and PUT requests would usually have a request body. GET and DELETE would not.

Request Headers
Request headers specify information such as the type of Browser, type of content in the message, and what type of response is accepted in return.

Example Request headers:

Content-Type: text/plain
User-Agent: Apache-HttpClient/4.5.4 (Java/1.8.0_144)

Request Body / Payload
A Payload is the body of the HTTP request or response.

A request body can be plain text, HTML, XML, JSON, Javascript, or a set of key-value pairs as form-data.

When browsing the Web, the Browser usually receives an HTML payload. This is the web page that you see rendered in the Browser.

Typically when working with an HTTP API we will send and receive JSON or XML payloads.

Not all HTTP messages can have payloads: POST and PUT can have payloads, GET and DELETE can not.

What is an HTTP Response?
When a request is sent to a server, the server returns a response. The response from the server tells you if your request was successful, or if there was a problem.

An HTTP response method is made up of three components: Response status code, response headers, response body.

Example response:

HTTP/1.1 200 OK
Content-Length: 859
Content-Type: text/html; charset=utf-8
Date: Fri, 23 Feb 2018 14:38:21 GMT
Server: Werkzeug/0.14.1 Python/3.6.3

What is a Web Service?
Applications which are accessed via HTTP APIs are often called Web Services. In other words, a web service is a function that can be accessed by other programs over the web (HTTP).


What is JSON?
JSON stands for JavaScript Object Notation and is a text representation that is also valid JavaScript code.

json %} { "employers":{ "employee":[ { "id":1, "name":"Dan Brown", "position":"Director", "status":"active", } ] } }

JSON can be thought of as a hierarchical set of key/value pairs where the value can be:
  • Object - delimited by { and }
  • Array - delimited by [ and ]
  • String - delimited by ” and ”
  • Integer
An array is a list of objects or key/value pairs. The keys are String values e.g. “employee”, “id”, “name”, etc.

Main Difference Between PUT and PATCH Requests
The main difference between PUT and PATCH requests are in the way the server processes the enclosed entity to modify the resource identified by the Request-URI.

In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced.

With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

Also, another difference is that when you want to update a resource with PUT request, you have to send the full payload as the request whereas with PATCH, you only send the parameters which you want to update.

If we want to change the first name then we send a PUT request for Update

{ "first": "Michael", "last": "Angelo" }
Here, although we are only changing the first name, with PUT request we have to send both parameters first and last. In other words, it is mandatory to send all values again, the full payload.

When we send a PATCH request, however, we only send the data which we want to update. In other words, we only send the first name to update, no need to send the last name.

For this reason, PATCH request requires less bandwidth.

Compare GET vs. POST

The following table compares the two HTTP methods: GET and POST.

 GETPOST
BACK button/ReloadHarmlessData will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
BookmarkedCan be bookmarkedCannot be bookmarked
CachedCan be cachedNot cached
Encoding typeapplication/x-www-form-urlencodedapplication/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
HistoryParameters remain in browser historyParameters are not saved in browser history
Restrictions on data lengthYes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)No restrictions
Restrictions on data typeOnly ASCII characters allowedNo restrictions. Binary data is also allowed
SecurityGET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
VisibilityData is visible to everyone in the URLData is not displayed in the URL


What are the phases involved in Software Testing Life Cycle?

The different phases involved in the software testing life cycle are:

PhasesExplanation
Requirement AnalysisQA team understands the requirement in terms of what we will testing & figure out the testable requirements.
Test PlanningIn this phase, the test strategy is defined. Objective & the scope of the project is determined.
Test Case DevelopmentHere, detailed test cases are defined and developed. The testing team also prepares the test data for testing.
Test Environment SetupIt is a setup of software and hardware for the testing teams to execute test cases.
Test Execution It is the process of executing the code and comparing the expected and actual results.
Test Cycle ClosureIt involves calling out the testing team member meeting & evaluating cycle completion criteria based on test coverage, quality, cost, time, critical business objectives, and software.

No comments:

Post a Comment