Accessing GraphQL using a Script or curl

GraphQL queries and mutations can be submitted using any suitable GraphQL client for programming language, such as Python or Node, or using a command-line tool such as curl. To use a scripting language you must keep the following in mind:

  • Use the appropriate URL for your LogScale instance. See LogScale URLs & Endpoints.

    For GraphQL the URL will always end in /graphql, e.g. cloud.humio.com:443/graphql.

  • Include the API token string in the header when submitting the request as part of the request header. For example, with curl you would add this to the command-line options:

    http
    -H "Authorization: Bearer api-token"

    Note

    API tokens provide access to different areas of the functionality according to the privileges within the token type. For example, to access and manage a repository you will need to use a repository API token, and the permission given to that token will allow (or limit) the abilities available through the GraphQL mutations when using that API token.

    See API Tokens.

  • Specify the request format (as JSON or ND-JSON) in the HTTP headers. For example in curl:

    http
    -H 'Content-Type: application/json'
  • Specify the HTTP request type as POST. In curl>

    http
    -X POST
  • Supply the query payload within an embedded JSON structure that specifies wheter the GraphQL request is a query or mutation.

    For example:

    http
    -d '{ "query" : "query {  dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}"}'

    Important

    The format of the submitted is payload is a key/value pair:

    json
    { "query" : "QUERYTEXT" }

    The content of the query should replace QUERYTEXT and this means that care should be taken to ensure that any quotes (") used in the query are properly escaped, otherwise the submitted JSON structure will be invalid. For example, the query used in the example above:

    graphql
    query {
      dynamicConfigs {
        dynamicConfigKey,
        dynamicConfigValue
      }
    }

    Has no quotes, and so can be embedded without issue. But this notification mutation contains quoted text strings:

    graphql
    mutation {
      notify(
        input: {
          target: All, 
          message: "Notification text", 
          severity: Warning, 
          notificationType: Bell, 
          dismissable: true, 
          title: "Warning!"
          }
      ) {
        message
      }
    }

    The quotes are party of the GraphQL Query and therefore need to be embedded as the value of the JSON payload. Quoting of special characters can be achieved using the backslash, i.e. using \" in place of ". The result, also converted to a single line:

    json
    { "query": "mutation{ notify(input: { target: All message: \"Notification text\" severity: Warning notificationType: Bell dismissable: true title: \"Warning!\"}) { message }}"}

    Further, when embedded into a command environment, for example curl curl, different quotes or quoting mechanisms must be used to ensure that the JSON payload, and the embedded GraphQL payload are distinct:

    Mac OS or Linux (curl)
    shell
    curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d @- << EOF
    {"query" : "mutation {
      notify(
        input: {
          target: All, 
          message: \"Notification text\", 
          severity: Warning, 
          notificationType: Bell, 
          dismissable: true, 
          title: \"Warning!\"
          }
      ) {
        message
      }
    }"
    }
    EOF
    Mac OS or Linux (curl) One-line
    shell
    curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d '{"query" : "mutation { notify( input: { target: All, message: \"Notification text\", severity: Warning, notificationType: Bell, dismissable: true, title: \"Warning!\" } ) { message } }" }'
    Windows Cmd and curl
    cmd
    curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql ^
        -H "Authorization: Bearer $TOKEN" ^
        -H "Content-Type: application/json" ^
        -d @'{"query" : "mutation { ^
      notify( ^
        input: { ^
          target: All,  ^
          message: \"Notification text\",  ^
          severity: Warning,  ^
          notificationType: Bell,  ^
          dismissable: true,  ^
          title: \"Warning!\" ^
          } ^
      ) { ^
        message ^
      } ^
    }" ^
    } '
    Windows Powershell and curl
    powershell
    curl.exe -X POST 
        -H "Authorization: Bearer $TOKEN"
        -H "Content-Type: application/json"
        -d '{"query" : "mutation {
      notify(
        input: {
          target: All, 
          message: \"Notification text\", 
          severity: Warning, 
          notificationType: Bell, 
          dismissable: true, 
          title: \"Warning!\"
          }
      ) {
        message
      }
    }"
    }'
    "http://$YOUR_LOGSCALE_URL/graphql"
    Perl
    perl
    #!/usr/bin/perl
    
    use HTTP::Request;
    use LWP;
    my $TOKEN = "TOKEN";
    my $uri = 'http://$YOUR_LOGSCALE_URL/graphql';
    my $json = '{"query" : "mutation {
      notify(
        input: {
          target: All, 
          message: \"Notification text\", 
          severity: Warning, 
          notificationType: Bell, 
          dismissable: true, 
          title: \"Warning!\"
          }
      ) {
        message
      }
    }"
    }';
    my $req = HTTP::Request->new("POST", $uri );
    $req->header("Authorization" => "Bearer $TOKEN");
    $req->header("Content-Type" => "application/json");
    $req->content( $json );
    my $lwp = LWP::UserAgent->new;
    my $result = $lwp->request( $req );
    print $result->{"_content"},"\n";
    Python
    python
    #! /usr/local/bin/python3
    
    import requests
    
    url = 'http://$YOUR_LOGSCALE_URL/graphql'
    mydata = r'''{"query" : "mutation {
      notify(
        input: {
          target: All, 
          message: \"Notification text\", 
          severity: Warning, 
          notificationType: Bell, 
          dismissable: true, 
          title: \"Warning!\"
          }
      ) {
        message
      }
    }"
    }'''
    
    resp = requests.post(url,
                         data = mydata,
                         headers = {
       "Authorization" : "Bearer $TOKEN",
       "Content-Type" : "application/json"
    }
    )
    
    print(resp.text)
    Node.js
    javascript
    const https = require('https');
    
    const data = JSON.stringify(
        {"query" : "mutation {
      notify(
        input: {
          target: All, 
          message: \"Notification text\", 
          severity: Warning, 
          notificationType: Bell, 
          dismissable: true, 
          title: \"Warning!\"
          }
      ) {
        message
      }
    }"
    }
    );
    
    const options = {
      hostname: 'http://$YOUR_LOGSCALE_URL/graphql',
      path: '/graphql',
      port: 443,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length,
        Authorization: 'BEARER ' + process.env.TOKEN,
        'User-Agent': 'Node',
      },
    };
    
    const req = http.request(options, (res) => {
      let data = '';
      console.log(`statusCode: ${res.statusCode}`);
    
      res.on('data', (d) => {
        data += d;
      });
      res.on('end', () => {
        console.log(JSON.parse(data).data);
      });
    });
    
    req.on('error', (error) => {
      console.error(error);
    });
    
    req.write(data);
    req.end();

When submitting a GraphQL query you include the query within the payload in different environments:

Mac OS or Linux (curl)
shell
curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d @- << EOF
{"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}"
}
EOF
Mac OS or Linux (curl) One-line
shell
curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}" }'
Windows Cmd and curl
cmd
curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql ^
    -H "Authorization: Bearer $TOKEN" ^
    -H "Content-Type: application/json" ^
    -d @'{"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}" ^
} '
Windows Powershell and curl
powershell
curl.exe -X POST 
    -H "Authorization: Bearer $TOKEN"
    -H "Content-Type: application/json"
    -d '{"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}"
}'
"http://$YOUR_LOGSCALE_URL/graphql"
Perl
perl
#!/usr/bin/perl

use HTTP::Request;
use LWP;
my $TOKEN = "TOKEN";
my $uri = 'http://$YOUR_LOGSCALE_URL/graphql';
my $json = '{"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}"
}';
my $req = HTTP::Request->new("POST", $uri );
$req->header("Authorization" => "Bearer $TOKEN");
$req->header("Content-Type" => "application/json");
$req->content( $json );
my $lwp = LWP::UserAgent->new;
my $result = $lwp->request( $req );
print $result->{"_content"},"\n";
Python
python
#! /usr/local/bin/python3

import requests

url = 'http://$YOUR_LOGSCALE_URL/graphql'
mydata = r'''{"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}"
}'''

resp = requests.post(url,
                     data = mydata,
                     headers = {
   "Authorization" : "Bearer $TOKEN",
   "Content-Type" : "application/json"
}
)

print(resp.text)
Node.js
javascript
const https = require('https');

const data = JSON.stringify(
    {"query" : "query {dynamicConfigs{ dynamicConfigKey, dynamicConfigValue }}"
}
);

const options = {
  hostname: 'http://$YOUR_LOGSCALE_URL/graphql',
  path: '/graphql',
  port: 443,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
    Authorization: 'BEARER ' + process.env.TOKEN,
    'User-Agent': 'Node',
  },
};

const req = http.request(options, (res) => {
  let data = '';
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (d) => {
    data += d;
  });
  res.on('end', () => {
    console.log(JSON.parse(data).data);
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(data);
req.end();

In each case, the above query should return a list of dynamic configuation variables (see Dynamic Configuration), formatted for clarity:

json
{
   "data" : {
      "dynamicConfigs" : [
         {
            "dynamicConfigKey" : "BlockSignup",
            "dynamicConfigValue" : "false"
         },
         {
            "dynamicConfigKey" : "DisableUserTracking",
            "dynamicConfigValue" : "false"
         },
         {
            "dynamicConfigKey" : "DisableAnalyticsJob",
            "dynamicConfigValue" : "false"
         },
         {
            "dynamicConfigKey" : "MaxAccessTokenTTL",
            "dynamicConfigValue" : "None"
         },
         {
            "dynamicConfigKey" : "RejectIngestOnParserExceedingFraction",
            "dynamicConfigValue" : "None"
         },
         ...
         }
    }
}

Mutations can be executed in the same way, using a prefix on the mutation:

Mac OS or Linux (curl)
shell
curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d @- << EOF
{"query" : "mutation {enableFeature(feature: RepeatingQueries)}"
}
EOF
Mac OS or Linux (curl) One-line
shell
curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"query" : "mutation {enableFeature(feature: RepeatingQueries)}" }'
Windows Cmd and curl
cmd
curl -v -X POST http://$YOUR_LOGSCALE_URL/graphql ^
    -H "Authorization: Bearer $TOKEN" ^
    -H "Content-Type: application/json" ^
    -d @'{"query" : "mutation {enableFeature(feature: RepeatingQueries)}" ^
} '
Windows Powershell and curl
powershell
curl.exe -X POST 
    -H "Authorization: Bearer $TOKEN"
    -H "Content-Type: application/json"
    -d '{"query" : "mutation {enableFeature(feature: RepeatingQueries)}"
}'
"http://$YOUR_LOGSCALE_URL/graphql"
Perl
perl
#!/usr/bin/perl

use HTTP::Request;
use LWP;
my $TOKEN = "TOKEN";
my $uri = 'http://$YOUR_LOGSCALE_URL/graphql';
my $json = '{"query" : "mutation {enableFeature(feature: RepeatingQueries)}"
}';
my $req = HTTP::Request->new("POST", $uri );
$req->header("Authorization" => "Bearer $TOKEN");
$req->header("Content-Type" => "application/json");
$req->content( $json );
my $lwp = LWP::UserAgent->new;
my $result = $lwp->request( $req );
print $result->{"_content"},"\n";
Python
python
#! /usr/local/bin/python3

import requests

url = 'http://$YOUR_LOGSCALE_URL/graphql'
mydata = r'''{"query" : "mutation {enableFeature(feature: RepeatingQueries)}"
}'''

resp = requests.post(url,
                     data = mydata,
                     headers = {
   "Authorization" : "Bearer $TOKEN",
   "Content-Type" : "application/json"
}
)

print(resp.text)
Node.js
javascript
const https = require('https');

const data = JSON.stringify(
    {"query" : "mutation {enableFeature(feature: RepeatingQueries)}"
}
);

const options = {
  hostname: 'http://$YOUR_LOGSCALE_URL/graphql',
  path: '/graphql',
  port: 443,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
    Authorization: 'BEARER ' + process.env.TOKEN,
    'User-Agent': 'Node',
  },
};

const req = http.request(options, (res) => {
  let data = '';
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (d) => {
    data += d;
  });
  res.on('end', () => {
    console.log(JSON.parse(data).data);
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(data);
req.end();

In the above, the output has been redirected to the file graphql.out. This will contain the output from the request that may include the result of the query, or any errors or warnings when the query or mutation was executed.