Transformation from a graphql query to a json query

In exploring the GraphQL example, I am wondering how to make a similar request with JSON in Javascript.

The GraphQL query in the example is:

{
  trip(
    from: {place: "NSR:StopPlace:5533" },
    to: {place:"NSR:StopPlace:5532"}
  ) 
    {
    tripPatterns{duration}
  } 
}

As per the documentation, the URL for querying is .

Here is my attempt in Javascript:

var url = "https://api.entur.io/journey-planner/v2/graphql";

var tripquery = 
{
    trip: 
    {
        __args: {
            from : {place :"NSR:StopPlace:5533" },
            to : {place :"NSR:StopPlace:5532" }                     
        },
        tripPatterns: {
            duration : true             
        }
    }
};

function jsonQuery(){

    var qry = JSON.stringify(tripquery);
    var url_qry = url + "?query=" + qry;

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", url_qry, true);
    xhttp.setRequestHeader("Content-Type", "application/json");

    xhttp.onreadystatechange = function(){
        console.log("onreadystatechange");
        if(xhttp.readyState === 4 && xhttp.status === 200){
            console.log("json-query-OK");
            console.log(xhttp.responseText);
        }
        else{
            console.log("xhttp.status      : " + xhttp.status);
            console.log("xhttp.statusText  : " + xhttp.statusText);
            console.log("xhttp.readyState  : " + xhttp.readyState);
            console.log("xhttp.responseType: " + xhttp.responseType);
            console.log("xhttp.responseText: " + xhttp.responseText);
            console.log("xhttp.responseURL : " + xhttp.responseURL);
            console.log("json-not-ok");
        }
    };



    xhttp.send();
    console.log("query sent");
}

The mentioned code will produce the following output in the console:

query sent
api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}:1 POST https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}} 400 (Bad Request)
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 2
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: 
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 3
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: No query found in the body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 4
query.js:38 xhttp.responseType: 
query.js:39 xhttp.responseText: No query found in the body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok

The __args in the Json object is a part I got from an online example, but it's still unclear to me how it functions.

I might need to refine my search queries, as I haven't been able to find a detailed explanation on how to translate a GraphQL query to a JSON object.

Answer №1

I encountered a similar issue, and here is how I solved it:

{
  c_con_tic_PTF(dz: CR, docmanId: 123) {
    docmanId
    dz
    data
  }
}

To execute this request as a curl command in macOS, you can refer to this guide: How to use CURL in macOS:

curl \
      -X POST \
      -H "Content-Type: application/json" \
      --data '{ "query": "{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }' \

   *my-graphicQL endpoint url*

By following these steps, I successfully obtained the desired response.

If you aim to create a similar graphQL query, you can structure it like this:

{ "query": "{  cz_atlascon_etic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }

To send the request using JavaScript, simply follow the same format. To offer additional assistance, here is how I executed the request in Java:

HttpRequest mainRequest =
HttpRequest.newBuilder()
.uri(URI.create("my graphQL endpoint"))
.POST(HttpRequest.BodyPublishers.ofString("{ \"query\": \"{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}\" }"))
.build();

Answer №2

To fetch data in JavaScript, utilizing the fetch API is a common method. Here is an example of how I typically approach it. Feel free to experiment by copying the code snippet below and executing it in Chrome Dev Tools.

async function fetchGraphQLData(url) {
    const queryObject = {
      query:
        '{ user(id: 123) { name } }',
    };
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(queryObject),
    });

    const json = response.json();

    return json;
}

async function fetchDataAsync() { 
  const data = await fetchGraphQLData('https://api.example.com/graphql');
  console.log(data); 
}
fetchDataAsync().catch(error => console.log('Error fetching data', error));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Decimal to RGB Values using JavaScript and PHP

Seeking assistance with converting a decimal value to an RGB value. Here is the formula I am using to compile the decimal value: c = r*(255*255)+g*255+b For instance, rgb(16,120,78) results in 1071078. What is the best way to solve for r, g, and b with ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

https://i.sstatic.net/j76vM.pnghttps://i.sstatic.net/EQPZO.png I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Does the success callback for AJAX operate synchronously?

Understanding that AJAX is asynchronous, a common question arises regarding the event execution within the success callback. Consider this scenario: $.ajax({ url : 'example.com', type: 'GET', success : (dataFromServer) { ...

Attempting to utilize express-load in conjunction with express 4

As a beginner in NodeJS, I encountered a problem with my code. Let me show you the issue. I am trying to load the application in the MVC pattern using express-load, but I am facing an error when defining the load order. Here is the important part of app. ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

There was an issue encountered while attempting to execute the command: npx create-next-app -e with-tailwindcss my-project

Every time I attempt to set up a new Next.js Tailwind 'App' using the command npx create-next-app -e with-tailwindcss my-project, I encounter the following issue: C:\socialmedia3>npx create-next-app -e with-tailwindcss socialmedia3 Creati ...

The Angular bootstrap popover vanishes as soon as the mouse hovers over it

Currently, I am facing an issue with an angular bootstrap popover on some text. The problem arises when the user tries to click on a link inside the popover as it disappears. Additionally, when changing from one popover to another, the previous one does no ...

Is there a workaround using jQuery to enable CSS3 functionality across all browsers?

Is there a way in jQuery to make all browsers act as if they have CSS3 capabilities? ...

Troublesome GSP: JavaScript not functioning properly in Gr

I am experiencing an issue with the JavaScript code I have. Here's my code: <script type="text/javascript"><!-- ​$(function () { $('#add').click(function() { $(this).before($('select:eq(0)').clone()); ...

Tips for converting intricate JSON nested data into CSV using Python?

I have a JSON dataset that I need to convert into a CSV file. Can someone assist me with the conversion process? Here is how the JSON dataset looks: { "123456": { "question_data": { "question_title": "How do I ...

How to check off a checkbox using a jQuery function

I have a listbox displayed in my view. This listbox is using a template Listbox <div id="UsersLoad" style="width: 50%"> @Html.EditorFor(i => i.Users, "UsersForEdit") </div> UserForEdit Template (Code snippet) @model string[] @{ ...

Understanding the process of unmarshalling an array within a POST request

I am attempting to send an array of JSON data with a POST request to an API server. However, I keep encountering the following error: cannot unmarshal array into Go value of type models.UserRequest Despite trying to unmarshal the data using a factory and ...

Retrieving data from a JSON file and utilizing it as a reference in a fresh dictionary

Currently, I am working with a Json file and looking to extract specific information from it to create a new dictionary. The structure of the json data resembles the following: { "code": "C568219u", }, "body_text" ...

How can we design the perfect JSON structure for this particular XML data?

Imagine this XML scenario: <Meters> <Meter> <Meter_ID>213</Meter_ID> <Reading1>74.00000</Reading1> <DateTime1>10/05/2011 09:00:18</DateTime1> <Reading2>73.00000</Reading2> & ...

Trouble arises when trying to load angular ui-bootstrap using require.js unless I change the name to ui.bootstrap

Code Overview: main.js: require.config({ paths: { 'uiBootstrap': '../lib/bootstrap/angular-bootstrap/ui-bootstrap-tpls.min' }, shim: {***}, priority: ['angular'], deps: ...

What could be the reason these two functions yield different outcomes?

I am currently in the process of optimizing a function to enhance performance. Previously, the old function took approximately 32 seconds, while the new one now only takes around 350 milliseconds for the same call. However, there seems to be an issue as th ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

The Ionic framework is showing an error that says "'LoginCtrl' is not defined as a function."

I encountered an issue while attempting to set up simple navigation in my ionic application. The error message I received was: "Argument 'LoginCtrl' is not a function, got undefined in the Ionic. What could be causing this problem?" Here is a sn ...

Is it possible to direct the user to a particular link upon swiping to unlock?

Hello everyone, I could use some assistance with this code. I am looking to redirect someone to a specific page when they swipe to unlock and automatically transfer them to another page when the swipe ends. Any help is greatly appreciated. Thank you! $ ...

Differences in window height between Firefox and Chrome

When positioning a modal vertically, how can I ensure consistent alignment across different browsers? method.center = function () { var top, left; top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2; left = Math.max($(window).widt ...