Edit Page

A Complex GraphQL App

🔧 Configuration

Sets localhost:8080 with admin:secret
Values are saved in your browser

Before running the tutorial

This tutorial assume:

  • RESTHeart Platform running on the localhost with the default configuration: the database restheart is bound to /, the user admin exists with default password secret, gql-apps is the collection, within restheart database, reserved to GraphQL apps definitions and the GraphQL service is reachable at /graphql.

  • The sample-mflix database (see Load Sample Data into MongoDB) is stored in the MongoDB instance associated to RESTHeart.

Create the GraphQL app

To create the gql-apps collection, run the following:

cURL

curl -i -X PUT "[INSTANCE-URL]/gql-apps" \
  -H "Authorization: Basic [BASIC-AUTH]"

HTTPie

http PUT "[INSTANCE-URL]/gql-apps" \
  "Authorization:Basic [BASIC-AUTH]"

JavaScript

fetch('[INSTANCE-URL]/gql-apps', {
  method: 'PUT',
  headers: {
    'Authorization': '[BASIC-AUTH]'
  }
})
.then(response => {
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

To upload the example GraphQL app definition, run the following:

Note
Due to the length of this GraphQL app definition, only the basic structure is shown. For the complete definition, see the full example at the end of this document.

cURL

curl -i -X POST "[INSTANCE-URL]/gql-apps" \
  -H "Authorization: Basic [BASIC-AUTH]" \
  -H "Content-Type: application/json" \
  -d @mflix-graphql-app.json

HTTPie

http POST "[INSTANCE-URL]/gql-apps" \
  "Authorization:Basic [BASIC-AUTH]" \
  "Content-Type:application/json" \
  < mflix-graphql-app.json

JavaScript

const mflixAppDefinition = {
  "_id": "mflix-gql-def",
  "descriptor": {
    "name":"MFlix",
    "description":"GraphQL App example using MongoDB sample_mflix dataset",
    "enabled": true,
    "uri":"mflix"
  },
  // ... complete schema and mappings
};

fetch('[INSTANCE-URL]/gql-apps', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic [BASIC-AUTH]',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(mflixAppDefinition)
})
.then(response => {
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

query with application/json

To execute a GraphQL request to Mflix app with Content-Type application/json, run the following:

cURL

curl -i -X POST "[INSTANCE-URL]/graphql/mflix" \
  -H "Authorization: Basic [BASIC-AUTH]" \
  -H "Content-Type: application/json" \
  -d '{
   "query":"query exampleOperation($year: Int!, $limit: Int = 0){MoviesByYear(year: $year, limit: $limit){ title comments{ text user{name} date} tomatoesRate}}",
   "variables":{
      "year":2008,
      "limit":2
   }
}'

HTTPie

http POST "[INSTANCE-URL]/graphql/mflix" \
  "Authorization:Basic [BASIC-AUTH]" \
  "Content-Type:application/json" \
  query="query exampleOperation(\$year: Int!, \$limit: Int = 0){MoviesByYear(year: \$year, limit: \$limit){ title comments{ text user{name} date} tomatoesRate}}" \
  variables:='{
    "year":2008,
    "limit":2
  }'

JavaScript

fetch('[INSTANCE-URL]/graphql/mflix', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic [BASIC-AUTH]',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "query": "query exampleOperation($year: Int!, $limit: Int = 0){MoviesByYear(year: $year, limit: $limit){ title comments{ text user{name} date} tomatoesRate}}",
    "variables": {
      "year": 2008,
      "limit": 2
    }
  })
})
.then(response => {
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Response
{
  "data": {
    "MoviesByYear": [
      {
        "title": "The Bank Job",
        "comments": [
          {
            "text": "Pariatur voluptatibus placeat quo architecto soluta non...",
            "user": {
              "name": "Shireen Baratheon"
            },
            "date": {
              "$date": 954044557000
            }
          },
          {
            "text": "Facilis ea voluptatem et velit rerum animi corrupti...",
            "user": {
              "name": "Lisa Russo"
            },
            "date": {
              "$date": 976465077000
            }
          }
        ],
        "tomatoesRate": 3.5
      },
      {
        "title": "The Flyboys",
        "comments": [],
        "tomatoesRate": 3.6
      }
    ]
  }
}

query with application/graphql

To execute a GraphQL request to Mflix app with Content-Type application/graphql, run the following:

cURL

curl -i -X POST "[INSTANCE-URL]/graphql/mflix" \
  -H "Authorization: Basic [BASIC-AUTH]" \
  -H "Content-Type: application/graphql" \
  -d '{
    MoviesByTomatoesRateRange(min: 3.8, max: 4.5, limit: 3, skip: 20, sort: -1){
        title
        comments {
            text
            user { name }
        }
        tomatoesRate
    }
}'

HTTPie

echo '{
    MoviesByTomatoesRateRange(min: 3.8, max: 4.5, limit: 3, skip: 20, sort: -1){
        title
        comments {
            text
            user { name }
        }
        tomatoesRate
    }
}' | http POST "[INSTANCE-URL]/graphql/mflix" \
  "Authorization:Basic [BASIC-AUTH]" \
  "Content-Type:application/graphql"

JavaScript

const query = `{
    MoviesByTomatoesRateRange(min: 3.8, max: 4.5, limit: 3, skip: 20, sort: -1){
        title
        comments {
            text
            user { name }
        }
        tomatoesRate
    }
}`;

fetch('[INSTANCE-URL]/graphql/mflix', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic [BASIC-AUTH]',
    'Content-Type': 'application/graphql'
  },
  body: query
})
.then(response => {
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Response
{
  "data": {
    "MoviesByTomatoesRateRange": [
      {
        "title": "The Wages of Fear",
        "comments": [
          {
            "text": "Commodi accusamus totam eaque sunt. Nihil reiciendis commodi molestiae esse...",
            "user": {
              "name": "Doreah"
            }
          }
        ],
        "tomatoesRate": 4.4
      },
      {
        "title": "Chicago Deadline",
        "comments": [
          {
            "text": "Nihil itaque a architecto. Illo veritatis totam at quibusdam. Doloremque...",
            "user": {
              "name": "Patricia Good"
            }
          }
        ],
        "tomatoesRate": 4.4
      },
      {
        "title": "The Passion of Joan of Arc",
        "comments": [],
        "tomatoesRate": 4.4
      }
    ]
  }
}