Tuesday, 27 July 2021

Query GraphQL API using JavaScript/JQuery

How to access GraphQl API using JQuery(AJAX).

Let's consider this sample GraphQL API:

Url: https://api.spacex.land/graphql/

Method: POST

Headers: {'Content-Type': 'application/json'}

Data:   provide your select list in JSON format like this: 

query:`{ 

                 launchesPast {

mission_name

launch_site {

  site_name_long

}

  }

}`

    }

You can quickly check its working by creating the below HTML file:

graphQlTest.html:
<html>
<head>
</head>
<body>
<button onclick="callAPI()"> Execute </button>
<p id="response-box"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
		function callAPI(){
		var url="https://api.spacex.land/graphql/";
		var method="POST"
		var body=JSON.stringify({ query:`{
				  launchesPast {
					mission_name
					launch_site {
					  site_name_long
					}
				  }
				}`});
		var headers={
		'Content-Type': 'application/json'
		}
		console.log("execution started");
            $.ajax({
                'method': method,
                'url': url,
		'headers':headers,
		'data':body,
                'success': function(data){
                    document.getElementById("response-box").innerHTML = JSON.stringify(data,undefined,2);
                }
            });

           }
	</script>  
</body>
</html>
 


The output of the HTML page looks like this:



On clicking the execute button, a javascript function associated with the button triggers the API call. The response from the API is in JSON format as follows:


Thank you!


Tuesday, 20 July 2021

CRUD operation on Rest API with Token based authentication

CRUD Operations on REST API with Token Authentication.

CRUD stands for Create, Read, Update, Delete which are most basic operations performed on any database. In REST API, we interact with database server using HTTP methods like GET, POST, PUT, DELETE etc,. to perform these operations. While dealing with any API, authentication plays a key role in restricting the access to authorized users. In the following example, I am using a token based authentication(JWT token to be more precise).

I am going to use two database tables to demonstrate all the 4 CRUD Operations of REST API using the concept of Token-based authentication.

For this I am using a free rest API:

Base url: https://restapiplayground.herokuapp.com

Let's understand the table structure before writing or reading data using API.

Database Schema:

There are two tables -

1.User

2.Todo

Schema of the User table looks like this:

  •     id=db.Column(db.Integer,primary_key=True)
  •     name=db.Column(db.String(100))
  •     public_id=db.Column(db.String(50),unique=True)
  •     password=db.Column(db.String(80))
  •     admin=db.Column(db.Boolean)

And schema of the Todo table looks like this:

  •     id=db.Column(db.Integer, primary_key=True)
  •     text=db.Column(db.String(100))
  •     complete=db.Column(db.Boolean)
  •     user_id=db.Column(db.Integer)
Steps to Access API:
  1. Generate a token using login url with the help of username and password.Request is shown in (fig.1) and Response is shown in (fig.2).Once the token is generated, it is valid for next 30 minutes.
  2. Pass this token as {"x-access-token":<token-value>} in JSON format in the headers for all the queries you perform on users and todo table.
  3. Set the parameters required for the API call like url, method,headers,Request- body.
  4. Send the request with appropriate method and parameters. Response is received from the server.

How to generate a token using login url with the help of username and password?

To perform any operations on these tables, you need to obtain a token.
Prerequisites: Need to have Login Access to the application with Basic Authentication i.e, Username, Password.
Request looks like this:


Fig. 1


Response looks like this:


Fig. 2

 
Once we get the token we can perform all the operations defined on these tables using the rest api.

Following endpoints are defined on User Table:

GET: 

1. To get all the users :

    URL:  https://restapiplayground.herokuapp.com/users
    method: GET
    Headers : pass token in json format with name "x-access-token"

    Request 
Response


2. To get a Specific User:

    URL:  https://restapiplayground.herokuapp.com/users/<user-id>
    method: POST
    Headers : pass token in json format with name "x-access-token"

                                        
                                                  Request


                                                    Response



POST

 1. Create a new User

    URL:  https://restapiplayground.herokuapp.com/users
    method: POST
    Headers : pass token in json format with name "x-access-token"
    Request body: provide data in format json format as shown below.


   Request


Response


2. Update existing User

    URL:  https://restapiplayground.herokuapp.com/users/<user-id>
    method: POST
    Headers : pass token in json format with name "x-access-token"
    Request body: provide updated details in format json format as shown below.


Request


Response

PUT:

1. Promote existing User as Admin (in this example)

    URL:  https://restapiplayground.herokuapp.com/users/<user-id>
    method: PUT
    Headers : pass token in json format with name "x-access-token"
   
                                            Request


Response


DELETE:

1. Delete existing User

    URL:  https://restapiplayground.herokuapp.com/users/<user-id>
    method: DELETE
    Headers : pass token in json format with name "x-access-token"
                                                         
                                                    Request
                


                                                    Response




Following endpoints are defined on Todo Table:

GET:

1. Get all the todos

    URL:  https://restapiplayground.herokuapp.com/todos
    method: GET
    Headers : pass token in json format with name "x-access-token"

                                                     Request
Response



2. Get a Specific todo 

    URL:  https://restapiplayground.herokuapp.com/todos/<todo-id>
    method: GET
    Headers : pass token in json format with name "x-access-token"

                                                Request


Response



POST

1. Create a new todo

    URL:  https://restapiplayground.herokuapp.com/todos
    method: POST
    Headers : pass token in json format with name "x-access-token"
    Request body: provide data in json format as shown below.



                                            Request


Response

2. Update an existing todo

     URL:  https://restapiplayground.herokuapp.com/todos/<todo-id>
    method: POST
    Headers : pass token in json format with name "x-access-token"
    Request body: provide updated details in format json format as shown below.


                                               Request


                                                Response

PUT:

1. Marks the todo as completed (in this example).

    URL:  https://restapiplayground.herokuapp.com/todos/<todo-id>
    method: PUT
    Headers : pass token in json format with name "x-access-token"

Request


Response


DELETE:

1. Delete existing Todo

    URL:  https://restapiplayground.herokuapp.com/todos/<todo-id>
    method: DELETE
    Headers : pass token in json format with name "x-access-token"

Request
                                                                   
                                                                             Response



 That is it for this Article. you can try out the API console available in the below     link:  

                                OR

  POSTMAN Desktop Application  to work on this API.

 Please let me know if you have any queries. 

 Please write to me in the below contact form if you want a user 
 login to begin with.

                                         Thank you!


Friday, 16 July 2021

How to test a Rest API without any tools like postman

How to test a Rest API without Postman

Most of the time, we have the need to test the functionality of an API without a third-party tool, as installing an API testing software is not always allowed in an organization.

As we all know, web applications that interact with APIs generally use technologies like javascript, jquery, Ajax to do all the CRUD operations(Create, Read, Update, Delete) on data within the website.

Since web browsers are able to execute the javascript, no other software is required to be installed on the machine in order to query an API.

Let's get started with a small piece of code that can get the API data at the click of a button.

To demonstrate this, I am using the below public rest API:

http://jsonplaceholder.typicode.com/users/1

you can simply browse the above url to see the JSON data which we are going to fetch using our script.

Implementation: Create an HTML file TestApi.html as shown below and run it with any web browser.

1. Get Request (Without Authentication): 

TestApi.html



<html>
	<head>
		<title>Test API with JavaScript</title>
	<script>
		function callAPI(){
		var url="http://jsonplaceholder.typicode.com/users/1";		
		var method="GET";
		var xhreq=new XMLHttpRequest();
		xhreq.onload=function(){
			document.getElementById("userdata").innerHTML = this.responseText;			
			}
		xhreq.open(method,url);
		xhreq.send();
		}

	</script>
	</head>
	<body>
		<br>
		<center>
		Click the button get json data<br><br>
		<button onclick="callAPI()" class="btn" style="background-color:green; color:white;"> Get Data </button>
		</center>
		<p id="userdata"></p>
	</body>
</html>

The output of the above code looks like this:

After clicking the Get Data Button, json data is loaded on the web page as shown below:

 The output json data we are expecting is displayed on the screen.That's it.

                                            Thank you!

                      

How to Integrate GraphQL API with Blue Prism

 GraphQL API - Blue Prism Integration This post discusses how to integrate GraphQL API with Blue Prism using a sample graphQL API and Utilit...