RESTFul API’s Testing Using Access Tokens along with Database Verification

Taimoor Pasha
12 min readApr 24, 2020

The Purpose of this article to make sure that all QA’s or any Tester can do API Testing in Both Manual and Automation as I did little project on RESTFul API’s using Python with flask and sqlalchemy and using PostgreSQL Database.

What we are going to need :

  1. Postman
  2. Any Database IDE which have ‘PostgreSQL’ (DBeaver recommended)

The advantages of this testing will be:

  1. Access Token Verification:

There are lot of other free sample API’s for testing purpose like reqres, dummy.restapi.com and many others but not many of them is provided with access token implementation as it is used for authentication of user.Thus that is major thing which is used in real world project and needs to be tested.

2. Back and Forth Database Verification:

Like access token’ case, Database verification is also not given to any user for verification of data and all verification we needed for this. So Database credentials will be provided to users with certain actions.

RESTFul API’s Methods:

Let’s have a basic introduction of important RESTFul API Methods, although many people are quite aware of this, but still we need to cover up just like refresher course.

Ok, Let’s make it quick and focus on types which we are dealing with this project.

GET:

GET request fetch all the information, which is necessarily required, it can fetch bunch of records or a single record.

POST:

POST request add or create a new record within the session.

PUT:

PUT request is used to update any existing record for which we can add multiple changes or leave it as it was earlier.

DELETE:

DELETE Request as the name suggests it deletes the records and once the record is deleted , it cannot be fetched or updated.

You Must be Thinking:

Primarily, in most of projects these four mainly are used and thus we will be working with that.

JWT’S Token:

For Access Tokens I have used JWT’s(pronouns as Jots) i.e. JSON Web Token, JWTs are an open, industry standard RFC 7519 method for representing claims securely between two parties. JWT supports multiple programming languages such as .NET, Java, Python, Node.js, JavaScript, Perl, Ruby and many others. Thus trending technique used for creating access tokens in current software industry.

Lets Discuss type of Tokens we are generating here:

Yeah, I know that’s stuff kind of boring but that’s how technical stuff works, you need to digest.

Access Token

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. Access Token will be generated every time we will login.

By default, an Access Token for a custom API is valid for 86400 seconds (24 hours).But we can accommodate time duration as per our requirement as we like. In this project, one access token will be valid till 60 minutes i.e. an hour.

Refresh Token

Now what happens an hour passed, do we need to login again with our credentials again. Simply not. Let’s take an example, if I have logged in to Facebook and using it for like 3–4 days, it wouldn’t be logging me out because there is a mechanism which is renewing access token again and again for which we are using our facebook and posting stuff. That mechanism is called ‘Refresh Token’.

A Refresh Token is a special kind of token used to obtain a renewed Access Token. You can …

Yeah I know its kind of getting bore, but that’s how things are , but once you are into it, you will get into technical depths

Anyways, so like I was saying that you can request new Access Tokens until the Refresh Token is blacklisted. Refresh Token will be generated along with Access Token every time we logged in and can be used up till 12 months but we are using it for 90 days (i.e. 3 Months).

We shall see below how they are created and how they can be used. But before that we shall discuss about what types of jwt authentication we are dealing with here:

  1. jwt_required

Important one and thus far frequent used in all of our major endpoints. It will be required our access token every time we are using for our major DML Operations such as Create, Update and Delete precisely.

2. jwt_refresh_token_required

Authentication requires refresh_token to fulfill our purpose and with that we can communicate with our API’s. We shall be using it for Refresh our Access Token only.

3. jwt_optional

JWT Authentication, where to get access to any API, access token is not neccessary, if user provides it that will be good but if not then authorization problem will not occur but limited data will be shown ;). Take the example of any shopping website, we can see multiple things but in order to add any item into cart we have to login or register our self, this is the idea of ‘jwt_optional’.

4. jwt_claims

Obviously you got to see everything, but if you does everything then what good admins are for ?Like in ‘Breaking Bad’ , Walter White says

Yes, there are certain activities which admins needs to perform and as he is the one who needs to get make calls and decisions for that.Now here jwt_claims came handy, and like there is only one king in a kingdom, there would be one admin for this purpose.

Pablo Escobar said it right. Go watch ‘Narcos’, ‘Wagner Moura’ nailed it by portraying ‘Escobar’.The performance of his lifetime I believe. One of the best series in ‘Netflix’ and its on streaming.

OK…

Lets get back to ‘REST API Testing’…

Since we have discussed all important RESTFul API’s Methods and token types as well, Lets Get Started with main stuff, Like Saul Goodman said

Back to back second reference to ‘Breaking Bad’, But this time from ‘Better call Saul’, Netflix is also streaming both ‘Better Call Saul’ and ‘Breaking Bad’.

OK Enough for series references…

Lets Start from registration, we have to provide email, password, first_name and last_name, where everything is important. So Using all time favorite for ‘Postman’.

As off now I am using for my localhost, but I will sure mention live server name at the end of this article or giving the link of documentation of all end points.

I have entered ‘email’, ‘password’, ‘first_name’ and ‘last_name’ respectively and send the response.

User have been created and we have to make sure that in database all the information has been entered or not.

So in User Table, user which we have created is displaying with all the information which we have entered.

Now, you can see, every information which we have added is showing as precisely as we have entered except for:

Yeah, password is different than what we have entered, its because we have hash_password library in order to encode your password and while logging in we will using the same password which we have entered and same library will be used to decode the password which is entered in database. We have to use it because there are some confidential data of user which we have to deal and not to give to anybody, not even Admin, so its for security purpose.

But Still Admin is Admin, he can do anything he likes.

Oh, But in that case Tywin Lannister was wrong, Admin is Admin, no matter what.

OK, Let’s Login the user and see what happens, for that we are going to use ‘Login’ end point and gonna enter ‘email’ and ‘password’ only.

After the Submitting the body as the request, the response will be like:

So Here is the response from server, where there is ‘access_token’ and ‘refresh_token’ as well, which we have discussed above.

That access_token will be up till 60 mints (1 hour)

That refresh_token will be till 90 days (3 months)

Lets deal with Refresh Token as I have talked above and promise to deliver some demo.

In order to get Refreshed Access Token, we have to use ‘refresh Token’ to get this one, for that you need to be little handy in postman as well.

You need to save value of ‘Refresh Token’ and ‘Access Token’ in postman, so that you don’t need to change it manually again and again.

Script is as below:

var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable(“access_token”, jsonData.access_token);
postman.setGlobalVariable(“refresh_token”, jsonData.refresh_token);

For all those, who said ‘Thanks’ in their heart

After submitting the request of Login, it will save the values of ‘access_token’ and ‘refresh_token’ in your environments, so that you can call the variable and leave the rest to postman. Reason why Postman is still best around for API Testing.

On Headers, I have called ‘Refresh token’ with ‘Authorization’ key by appending it with ‘Bearer’ text. Bearer text is used in postman if we have to add authorization key for our API. So that’s important.

Now we are sending the request:

We have another access_token, remember we can use that ‘Access_token’ any time we can use within 90 days, but it is most recommended to use when our token is expired.

Now we will have to do some data insertions and do some API Testing which is much more than of Login.

Lets Talk about of Adding a new Artist since everyone is music fans and no one can past their day with it.

We will talk about our authentication types as well here, so be ready for that.

Adding an Data

Now we are going to add ‘Artist’ and have to check that whether that Artist have been added on database as well, like I have said, we are going to verify with Database back and forth.

Since I have mentioned above that in all Major operations i.e. POST, PUT and DELETE i.e. Create, Update and delete we are gonna need to add access_token, so as I did in creating an artist.

Let’s add new artist i.e. ‘Maroon 5’ as I am listening quite of his songs.

Animals — Maroon 5

If anyone wondering name of song, its posted :| just sharing , Ok, let’s post it.

So our Artist have been added and we have to make sure that same data has been added on Database as well or not.

Now you can see that with exact same data, data is present in database as well id, name and created_date along with other data.

Viewing all Artist from jwt_optional

Now Lets see we have to view all the artist we have created, for that we are going to use ‘all_Artists’ end point which will display us all the names and we have implemented ‘jwt_optional’ on this call as well, so let’s see what happens.

First we are going to get all artists, without entering access_token, like image on above and the response will be like:

Like message is displaying i.e. ‘More data can be display if you enter access_token’, and which is possible when you are login with your correct and authentic credentials.

Now we are going to add access_token to the same end point to check whether it delivers us all data which is present within database.

Now we have entered access_token we can view that we are able to view all artists we have created, and this implementation is done on all Get all results end points.

Perform an activity having jwt_claims:

We can perform everything in our end points like to get data, add data, delete data some with access_token and some without access_token, but like I said there are some things which King needs to do here.

King here is metaphor is for Admin.

OK, let’s get started with this one, Now this is just for the sake of example, like there is only one king i.e. admin, so I have implemented jwt_claims in Delete an artist.

for that we are going to login with user who is not an admin and we are going to delete an artist.

Now from the above picture, you can see that we have provided access_token but yet we are unable to delete an artist because we are not an admin and yet we can’t perform this activity.

Now we are going to login with admin and delete this, using access_token and using valid artist_id

So, Artist has been deleted and verify that on Database as well

Artist with id 14 is deleted and that artist was ‘Backstreet Boys’.

Database Credentials are as follow:

Server : ec2–52–87–135–240.compute-1.amazonaws.com

Database : d6r6fioeluiou0

Username : ihguupxpsovmpu

port: 5432

Password : d84096d66a5ab9beea2c56a19bb1ab51dbfd96e1f662c681adeff80b370a1bae

Documentation of all end points are mentioned here.

So these are jwt implications we have done in this project, if somebody wants to work in this and want to add new feature as developer or learn something, here is the link of GitHub Link of this project.

Hope to see you Guys in any other article, which will be same with gifs and learning.

If liked the post mail me

taimoor_pasha2009@outlook.com

Or Follow me at Linkedin here.

--

--

Taimoor Pasha

Software Automation Expert | Programming Enthusiastic