End to End API Testing in PyTest

API (Application Programming Interface) is a set of rules which are already defined that instruct how computers or applications communicate to each other.

Almost every applications and computer are dependent on API which reduces complications from the data transfer process. Hence API testing plays a vital role in testing because if a single API fails it disturbs the whole system. API testing is broadly classified into two categories:

  • Manual Testing – If a human manually executes an API and verifies their test cases, generates the test reports it is called manual testing.
  • Automation Testing – If the machine automatically executes API and verifies the test case and generates the test results it is called automation testing.

In this tutorial, we will understand API testing by creating a small database using a python dictionary and understanding API calls by using the python function.

Basic Flow For API automation Testing

This algorithm will be used for automated API testing.

  1. Start
  2. Call the API by giving input parameters.
  3. Check the response given by the API.
  4. if the actual response matches the expected response the test will pass.
  5. Else the test will get fail.
  6. End

End to End API automation Testing in PyTest

Create a python file with the name test_database.py. In the file first, create a database using a python dictionary.

database={
    1:['ram','A',56,80],
    2:['Shyam','B',45,67],
    3:['Gita','C',45,78],
    4:['Mohan','D',67,20]
}

Now let’s create a python function that simulates an API that reads data from the database. if the input data matches from the database the function will return 200 and the message will be there “Read Operation Successfully”  the test case will also get passed else it will return 404 and the message will be there “player does not exist”.

def read_player(payload):
    id = payload['Player_id']
    if id in database:
        entry=database[id]
        return {'Code':200,
        'Response':{'Name':entry[0],'Team':entry[1],'Age':entry[2],'Average':entry[3]},
        'Message':'Read Operation Succesfully'}
    else:
        return {'Code':404,'Message':'Player does not exists'}

Now, create a test function that will test the database and API using the pytest framework. test_payload is the input given to test functions.

test_payload={
    'Player_id':4
}
def test_read_player():
    response= read_player(test_payload)
    assert response.get('Code')==200

We can execute the test_database.py file using the command pytest test_database.py. Hence the test case passed Successfully.

Thus in this tutorial, we have tested an API using the pytest framework and learned how to create API responses using the python function.