Use TakeShape with Node.js
It's easy to call your API from within your Node.js application.
The first thing you'll want to do is create a .env
file in your project that includes the secrets TAKESHAPE_ENDPOINT
and TAKESHAPE_API_KEY
:
TAKESHAPE_ENDPOINT=xxxxx
TAKESHAPE_API_KEY=xxxxx
When you're in your project in the TakeShape web client, you can find your project's endpoint in the sidebar of the API
tab. Copy it into your .env
file.
You can also create an API Key from within the API tab. Pick the dev
permission for your key, then
save it. After saving, you'll be presented with a one-time secret string. Copy it into your .env
file.
Once you've got your secrets, install some libraries to help make your request:
npm i --save node-fetch dotenv
Now, querying TakeShape is as simple as making an asynchronous network request:
// Use `dotenv` to load your environment variables
require('dotenv').config();
const fetch = require('node-fetch');
async function query(query, variables) {
// Every request to GraphQL uses the `POST` method
const res = await fetch(process.env.TAKESHAPE_ENDPOINT, {
headers: {
Authorization: `Bearer ${process.env.TAKESHAPE_API_KEY}`
},
method: 'POST',
body: JSON.stringify({query, variables})
});
return res.json();
}
// Write GraphQL queries as strings
const COUNTRY_QUERY = `
query Country($code: ID.) {
Countries_country(code: $code) {
name
emoji
currency
capital
}
}
`;
// Make the request, then log out the resolved data
// Here, we'll query for data about Japan using its country code, `JP`
query(COUNTRY_QUERY, {code: 'JP'}).then(data => console.log(data));
Run this file with node takeshape.client.js
and you'll see it return your data.
{
"data": {
"Countries_country": {"name": "Japan", "emoji": "🇯🇵", "currency": "JPY", "capital": "Tokyo"}
}
}