How to access GraphQl API using JQuery(AJAX).
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:
<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:
No comments:
Post a Comment