Getting started with JavaScript

Alerts API querying example with JavaScript

Request code

To query the API, you can use any HTTP client of choice or any specialized GraphQL API Clients, like graphql-request, urql, or Apollo.

Using a client compatible with Fetch API, the request could be issued with the following code:

Make sure to replace qfNfdijpFhbhPhA7j2ZxvtEGkfv8DftTtmTEbnWN with your unique API key.

const fetch = require('isomorphic-fetch');
const API_KEY = 'qfNfdijpFhbhPhA7j2ZxvtEGkfv8DftTtmTEbnWN';
const API_ENDPOINT = 'https://api.craft.co/v1/query';
const GRAPHQL_QUERY = /* GraphQL */`
query getAlerts($first: Int!) {
alerts(first: $first) {
id
dataset
variable
}
}
`;
requestHeaders = { 'Content-Type': 'application/json', 'x-craft-api-key': API_KEY };
requestData = { 'query': GRAPHQL_QUERY, 'variables': { 'first': 3 } };
const result = await fetch(API_ENDPOINT, {
method: 'POST',
headers: requestHeaders,
body: JSON.stringify(requestData),
});
const { data, errors } = await result.json();
console.log(data);

Response

The above command returns JSON structured like this:

{
"data": {
"alerts": [
{
"id": "8da58037-d0b9-8365-75b4-6754aed4e9b0",
"dataset": "news",
"variable": "news_article"
},
{
"id": "8489a57b-7be9-0364-a95d-65ad84ed430a",
"dataset": "news",
"variable": "news_article"
},
{
"id": "8489a57b-7be9-0364-a90d-65ad84ed430a",
"dataset": "news",
"variable": "news_article"
},
...
]
}
}

Read more