API Testing in selenium python

I have been trying to explain this api in simple way but somehow I was having difficulty but finally got an explanation in simple terms, so if something is wrong with explanation please do forgive me.

socket-api-selenium I hope You have seen this thing in your everyday life, if not ( at least you must be sure that this is not a lemon ).

This is an Indian electrical socket, if you are from another county then instead of circle rounds then you might have come across vertical ones.

certainly I am not electrical engineer but Mechanical engineer

An API is nothing but similar to electrical socket

This socket provides 240V power supply, we can connect electrical devices like fan, TV, Washing Machine, Radio, Air Conditioner and so on.

different-connections-to-api Similar to this socket is api exposes an URL, to which different websites can connect and those website could be developed using different technologies. Major use of the api is exposing and modifying the data.

Fan, RAdio, TV are developed for different purposes but they will connect to same Socket and they will achieve their purpose either by adjusting voltage.

Similarly, using api the developers will build their application and UI based on their website need and manipulate it.

standard-api-selenium Can you guess, Which take less time to execute UI or API ?
You are right, The one which doesn't have UIless i.e API.

It doesn't mean every website will have API, based on the functionalities developers use APIs, usage of API is solely dependent on the business.

How API testing Works

API testing is not a big deal, as everyone say you have to test the URL and check the Response body and response status code.

Is it All about API Testing ? Nah, testing an URL is a first part of API Testing. API testing couple of stages ( I am not sure number of stages that is why mentioned 'couple').

API is tested in multiple stages but all these stages are solely dependent on your team and organization.

  1. Hit the API url for the given data (unique id or something)
  2. Check the database for the same data with hat unique id
  3. Navigate to the UI of the API and verify the details of the product
  4. Hit the API URL with required Operation, Operations could be Post, Put, Delete
  5. Hit the GET url of the API and verify the changes
  6. Test the database whether API operation is successful, and data is changed or removed
  7. Navigate to the UI of the API and verify the product details

We would be performing individual operations and once we learn we will learn API Testing processes, then we would be doing all above mentioned scenario

Our API URL for APi Testing with Python Selenium

I don't want my reader to depend on the third-party APIs, because of which I have created a dummy API (I am not developer so please do expect some issues and error).

my-api-design I have created this api using the tutorial and example present in the Internet, this API has following features.

  • This API is built using PHP and angular with reach
  • You can create products using this API
  • You can delete the created Product or exiting Products
  • You can edit new/Existing products
  • This API it not behind authentication
  • You can view all the products or a specific products bases on id, name, price but you cannot mix them.
  • You are not restricted to perform any operation on this api and it doesn't restrict sharing or performing changes
  • This API has an UI at : https://chercher.tech/sample/api-ui

Apart from these thanks to gitHub, and I want you to perform or test the functionalities of the API UI using above URL so that you will be familiar with operations

The UI and the APi both point to the same place in Db and the only change is how these call the target.

It is something like we can call a person with first name as well as with second name, if no other person is with same name. But you cannot do the same thing with my name because 3 out of 10 people have my name. silly.

Below are few End points of our api, these end point change from product to product and sometimes some products will have only one end point for all the urls

Sample API for GET all : https://chercher.tech/sample/api/product/read

Sample API for GET Specific: https://chercher.tech/sample/api/product/read?id=90

Sample API for PUT : https://chercher.tech/sample/api/product/create

Sample API for POST : https://chercher.tech/sample/api/product/update

Sample API for DELETE : https://chercher.tech/sample/api/product/delete

Manipulate the API using just URL bar :


Sample API for GET all : https://chercher.tech/sample/api/product/read

Sample API for GET Specific: https://chercher.tech/sample/api/product/read?id=50 instead of ?id you ca also use name or price wit respective value, you must not use any single/Double quotes in url even for string parameters as well.

Sample API for PUT : https://chercher.tech/sample/api/product/create?name=xyz&description=desc of xyz&price=30

Sample API for POST : https://chercher.tech/sample/api/product/update?id=40&name=xyz&description=desc of xyz&price=30

Sample API for DELETE : https://chercher.tech/sample/api/product/delete?id=50

requests binding with Selenium Python

Request package provides the capability to handle the api operations like
  • GET
  • POST
  • DELETE
  • PUT
Install the request module using below npm command.

pip install requests
requests-python-api-testing-selenium

GET method in api with Python Selenium

The GET method is used to extract information from the given server using a given URI. While using GET request, it should only extract data and should have no other effect on the data.

You can use the requests.get() function to get the details from the Api.

status_code property will fetch the status code for the operation based on the status code we can decide that whether the test is failed or not.

End Point : https://chercher.tech/sample/api/product/read

Below URL, will only return the details for the id 90 :
End Point : https://chercher.tech/sample/api/product/read?id=90


import unittest
import requests

class Test(unittest.TestCase):

    def test_write_csv_file(self):
        r = requests.get("https://chercher.tech/sample/api/product/read?id=90")
        print(r.json())
        print(r.status_code)
                    
if __name__ == "__main__":
    unittest.main()
read-api-selenium-python

Put method in request with python

Put method is different from get() method, put method creates details or resource the server/database.

It is upto the developer whether an end point API url support the both Create an Update or either of them, the API we are using in below example will create the resource but will not have capability to update

When the target resource exists it overwrites that resource with a complete new body. That is PUT method is used to CREATE or UPDATE a resource.

Status Codes of PUT

  • 201 OK: The request was successful, we updated the resource and the response body contains the representation.
  • 202 ACCEPTED: The request has been accepted for further processing, which will be completed sometime later.
put method is like an UPDATE query in SQL which inserts or updates a record depending upon whether the given record exists
put() method in API may return 201 status code with message 'Created' if everything is successful.

import unittest
import requests
import json

class Test(unittest.TestCase):

    def test_write_csv_file(self):
        api_url = " https://chercher.tech/sample/api/product/create"
        
        data = json.dumps({'name':'test', 'description':'some test repo'})
        resp = requests.put(api_url, data)
        print(resp)
                    
if __name__ == "__main__":
    unittest.main()

Console output response-api-result-python-selenium


Now just visit, UI of the api at https://chercher.tech/sample/api-ui put-method-api-python-selenium

POST API Method in Request with Python Selenium

"Post" means "after"; if you have a collection of entities and you tack a new one onto its end, you have posted to the collection.

You can't post an existing entity, and it's common (though not always required) to use the collection’s URI to post.

Status Codes of POST

  • 201 OK: The request was successful, we updated the resource and the response body contains the representation.
  • 202 ACCEPTED: The request has been accepted for further processing, which will be completed sometime later.
post method is like an INSERT query in SQL which always creates a new record in database.

End Point: https://chercher.tech/sample/api/product/update

Every API will provide some uniquely parameter for every product, using that parameter we have to update the details for this example I would be using id Below program will update the details of the product which has id as 174


import unittest
import requests
import json

class Test(unittest.TestCase):

    def test_write_csv_file(self):
        api_url = "https://chercher.tech/sample/api/product/update"
        
        data = json.dumps({'id':174, 'name':'twinkle', 'description':'some test repo'})
        resp = requests.post(api_url, data)
        print(resp)
                    
if __name__ == "__main__":
    unittest.main()


Verify whether details got updated or not, using API https://chercher.tech/sample/api/product/read response-post-method-selenium-python-api-testing


You might want to verify the Ui of the Api.,
Visit : https://chercher.tech/sample/api-ui post-method-selenium-python

Delete method in API

DELETE- Removes data from the target resource/ database given by a URI.

Status Code of DELETE

  • 202 ACCEPTED: The request has been accepted for further processing, which will be completed sometime later.
  • 204 OK: The request was successful; the resource was deleted.
delete method is like a DELETE query in SQL which inserts or updates a record depending upon whether the given record exists
delete-api-rest-selenium

import unittest
import requests
import json

class Test(unittest.TestCase):

    def test_write_csv_file(self):
        api_url = "https://chercher.tech/sample/api/product/delete?id=50"
        resp = requests.delete(api_url)
        print(resp)
                    
if __name__ == "__main__":
    unittest.main()		


Verify whether details got updated or not, using API : https://chercher.tech/sample/api/product/read You might want to verify the Ui of the Api, Visit : https://chercher.tech/sample/api-ui

PATCH

PATCH is used to partially update an existing entity with new information. You can’t patch an entity that doesn’t exist. You would use this when you have a simple update to perform, e.g. changing a user’s name.

patch method is like an UPDATE query in SQL which sets or updates selected columns only and not the whole row.

HTTP codes

HTTP Status Codes

Before diving into the communication with other APIs, let's review the HTTP status codes we may encounter during the process. They describe the outcome of our requests and are essential for error handling.

  • 1xx - Informational
  • 2xx - Success: These status codes indicate that our request was received and processed correctly. The most common success codes are 200 OK, 201 Created and 204 No Content.
  • 3xx - Redirection: This group shows that the client had to do an additional action to complete the request. The most common redirection codes are 301 Moved Permanently, 304 Not Modified.
  • 4xx - Client Error: This class of status codes is used when the request sent by the client was faulty in some way. The server response usually contains the explanation of the error. The most common client error codes are 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict.
  • 5xx - Server Error: These codes are sent when the server failed to fulfill a valid request due to some error. The cause may be a bug in the code or some temporary or permanent incapability. The most common server error codes are 500 Internal Server Error, 503 Service Unavailable.

If you'd like to learn more about HTTP status codes, you can find a detailed explanation about them here. ​

Api Testing vs Unit Testing

API Testing

  • API testing is done by testers.
  • In API testing we test end to end functionality.
  • Tester not allowed to access the source code.
  • Testing can be done after build is created.
  • Broader in scope.

Unit Testing

  • Unit testing is done by developers.
  • Developers can access the source code.
  • In unit testing separated functionality tested.
  • Usually ran before check-in
  • Limited in scope.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
You can also share knowledge by Adding a topic here


Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link for the training starting from 15th Nov 2018
 
Join My Facebook Group
Join Group