Skip to main content

Query Prismatic's API with NodeJS

When querying Prismatic's GraphQL API from JavaScript or TypeScript, you can either use a generic HTTP client (like the fetch API), or you can reach for a GraphQL client library, like graphql-request. We'll cover both examples here.

Querying Prismatic's API using fetch

First, generate an authentication token. Then, send an HTTP request to https://app.prismatic.io/api. The body of your request should be JSON with a query that represents the query or mutation you want to run, and optional variables if you are running a parameterized query.

const fetch = require("node-fetch");

const token = "YOUR_TOKEN";
const apiEndpoint = "https://app.prismatic.io/api";

const query = `
query {
components {
nodes {
label
description
key
}
}
}
`;

fetch(apiEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ query: query }),
})
.then((r) => r.json())
.then((data) => console.log("data returned:", data));

Querying Prismatic's API using graphql-request

First, install required dependencies.

npm install graphql graphql-request

Then, initialize and run a query. In this example, our query is parameterized using GraphQL variables, and we search for only components with the key "slack":

import { gql, GraphQLClient } from "graphql-request";

const PRISMATIC_API_ENDPOINT = "https://app.prismatic.io/api";
const PRISMATIC_API_KEY = "REPLACE_ME";

async function main() {
const client = new GraphQLClient(PRISMATIC_API_ENDPOINT, {
headers: {
Authorization: `Bearer ${PRISMATIC_API_KEY}`,
},
});

const query = gql`
query ($myKey: String!) {
components(key: $myKey) {
nodes {
label
description
key
}
}
}
`;

const result = await client.request(query, { myKey: "slack" });
console.log(JSON.stringify(result));
}

main();