API testing with Bearer token

 

API testing with Bearer token 


HTTP Authentication Schemes:

  HTTP Authentication verifies the user's eligibility to access the web resource. It involves HTTP header-based communication between the client and the server, with the server requesting the user's credentials for authentication.




I'll start by writing about bearer tokens because I recently learnt about them. 



 When a user logs in, the authentication server generates a token known as a bearer token. This token should be sent in the header of the client's subsequent calls .This token will shortly expire; in such circumstances, a new token must be generated.



Application using Bearer token:


The Contact List App is a small program that Kristin Jackvony created for testing. The APIs for this application authenticate users using bearer tokens.


API documentation can be found https://documenter.getpostman.com/view/4012288/TzK2bEa8


I started by exploring the app's functionality , making a list of prospective test scenarios.


  1. The User signups with an email and password. 

  2. Then with that User id, login to the application. 

  3. Add contacts (First Name,Last Name are required fields), Date of birth, Email,Phone ,Address 1, City,State,Postal code, Country. 

  4. The added contact can be edited (First Name,Last Name are required fields) and other fields are not mandatory.

  5. Delete a contact.

  6. Viewing User’s profile, Editing and Deleting user can not be done from the UI. Per documentation, this can be done via API.


 




















For my API testing, I also used the same test scenarios.


API test cases:

Use Case 1

Login  to get Bearer Token

API Documentation

https://documenter.getpostman.com/view/4012288/TzK2bEa8#3ec4f31e-3ce0-4edf-9f3a-e3ec6461e4e6

HTTP Verb 

Post

Payload

Username and Password  as JSON

Headers

Content-Type: 'application/json

URL

https://thinking-tester-contact-list.herokuapp.com/users/login


Expected Response:


Status Code 

200 OK, if login is successful.

Response Cookie 

Token


I did this in Python as well:


Use Case 2

Create a new User

API Documentation

https://documenter.getpostman.com/view/4012288/TzK2bEa8#bcd848eb-d7ae-4b73-9a0c-59eb2254017e

HTTP Verb 

Post

Headers

Content-Type: 'application/json

Authorization : Bearer token.

URL

https://thinking-tester-contact-list.herokuapp.com/users

Body/Payload

Body: 

   {

    "firstName": "Test",

    "lastName": "User",

    "email": "test@fake.com",

    "password": "myPassword"

}



I discovered that this “create User” API needs a Bearer Token as I read the API documentation. I had to login with a user I created from the UI in order to obtain the Bearer token. I therefore made the POST API Login call and received the bearer token in return. When creating a user API request, use this token:




In Python:


Use Case 3

Add new contact

API Documentation

https://documenter.getpostman.com/view/4012288/TzK2bEa8#abe537df-fccc-4ee6-90d2-7513e3024d6b

HTTP Verb 

Post

Payload

{

    "firstName": "John",

    "lastName": "Doe",

    "birthdate": "1970-01-01",

    "email": "jdoe@fake.com",

    "phone": "8005555555",

    "street1": "1 Main St.",

    "street2": "Apartment A",

    "city": "Anytown",

    "stateProvince": "KS",

    "postalCode": "12345",

    "country": "USA"

}

Headers

Content-Type: 'application/json

Authorization : Bearer token.

URL

https://thinking-tester-contact-list.herokuapp.com/contacts


Here also use the same bearer token we received for the new user we created in Use Case 2.





Here, ADD contact test can be sent with only the required fields, without the required fields, with valid and invalid data, etc..


Once the contact was created, I sent a GET request with the contact ID retrieved from ADD contact to verify the contact's creation. 


Then I updated the contact with the contact ID retrieved from ADD contacts.

Similarly I deleted the added contact as well. 

Updating, and deleting user profiles would be added later to the tests.

The full code 

import requests

import json

import random


contact_id={}

bearer_token = ""

user_name ="nsuba.skannan@gmail.com"

new_user = "ab"+str(random.randint(1,1000))+"@abc.com"


# This function logs in to contact list application and returns bearer token for the user.

# The token is sent in headers of all other actions :

# Add user,Add a new contact to the list, get the new contact ID,Update the newly created contact

# Delete the newly created contact



def user_login(user_name):

   url = "https://thinking-tester-contact-list.herokuapp.com/users/login"

   payload = json.dumps({

       "email": user_name,

       "password": "Sivaom1$"

   })

   headers = {'Content-Type': 'application/json'}

   response = requests.request("POST", url, headers=headers, data=payload)

   json_response = response.json()

   #print (response.text)

   bearer_token = json_response['token']

   #print(bearer_token)

   return bearer_token


#add New user

def addUser_profile():

   url = "https://thinking-tester-contact-list.herokuapp.com/users"

   token = user_login(user_name)


   payload=json.dumps({

   'firstName': 'fkjhjk',

   'lastName': 'fkgjlk',

   'email': new_user,

   'password': 'Sivaom1$'

   })


   headers = {

       'Authorization': 'Bearer '+token,

       'Content-Type': 'application/json'

   }

   print (payload)

   response = requests.request("POST", url, headers=headers, data=payload)

   print(response.text)


def getContacts():

   url = "https://thinking-tester-contact-list.herokuapp.com/contacts"

   token=user_login(new_user)

   payload = {}

   headers = {

       'Authorization': 'Bearer '+token

   }

   response = requests.request("GET", url, headers=headers, data=payload)

   print("Contacts List")

   print(response.text)



def addContacts():

   url = "https://thinking-tester-contact-list.herokuapp.com/contacts"

   token = user_login(new_user)

   #print(token)


   payload = json.dumps({

       "firstName": "John",

       "lastName": "Doe",

       "birthdate": "1970-01-01",

       "email": "jdoe@fake.com",

       "phone": "8005555555",

       "street1": "1 Main St.",

       "street2": "Apartment A",

       "city": "Anytown",

       "stateProvince": "KS",

       "postalCode": "12345",

       "country": "USA"

   })

   headers = {

       'Authorization': 'Bearer '+token,

       'Content-Type': 'application/json'

   }

   response = requests.request("POST", url, headers=headers, data=payload)

   print("New Contact Added: ")

   print(response.text)

   json_response = response.json()

   contact_id["id"]=json_response["_id"]




def updateContact():


   url = "https://thinking-tester-contact-list.herokuapp.com/contacts/"+contact_id['id']

   token = user_login(new_user)

   payload = json.dumps({

       "firstName": "Nathan"

   })

   headers = {

       'Authorization': 'Bearer ' + token,

       'Content-Type': 'application/json'

   }

   response = requests.request("PATCH", url, headers=headers, data=payload)

   print("New Contact Updated: ")

   print(response.text)



def deleteContact():

   url = "https://thinking-tester-contact-list.herokuapp.com/contacts/"+contact_id['id']

   token = user_login(new_user)


   headers = {

       'Authorization': 'Bearer ' + token,

       'Content-Type': 'application/json'

   }

   response = requests.request("DELETE", url, headers=headers)

   print(response.text)


addUser_profile()

addContacts()

getContacts()

updateContact()

getContacts()

deleteContact()

getContacts()


Comments

Popular posts from this blog

API Testing journey