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!


No comments:

Post a Comment

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...