Skip to main content

Use TakeShape with Vanilla JavaScript

By far the easiest and simplest way to use TakeShape is with vanilla JS. Whatever your reasons, if you need to pull data from TakeShape's API Mesh into your vanilla JS code, this is the guide for you.

Connecting your TakeShape Project

To connect to your TakeShape project, you need your API Endpoint and an API key.

If you haven't created a TakeShape project yet, follow this guide to do so.

If you already have a project, your API Endpoint will be in the TakeShape web client. In the home tab, look for the "Useful Snippets" section.

Copy the API Endpoint and save it somewhere secure.

To get an API Key, you'll have to create one. Read our docs on creating an API Key here.

danger

API keys used in frontend applications are exposed to the browser, even if you use environment variables. When you create an API Key, always use the fewest permissions necessary for your application. Learn more in our permissions guide.

Setting up an vanilla JS project

Setting up a vanilla JavaScript project is simple, really. Navigate to the folder where you'd like the project to be, then create a new folder there and name it what you want. Open that folder in your favorite IDE, and we'll begin.

For this example, we'll be injecting Ecommerce data into an HTML page after retrieving it from our TakeShape backend.

Creating an HTML file

Create a file called index.html in the root of your project directory.

Here's what our HTML will look like for this example:

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TakeShape Vanilla JS Example</title>
</head>
<body>
<h1>Products List:</h1>
<ul id="resultsContainer">

</ul>
</body>
<script src="takeshape-example.js"></script>
</html>

The most important points in the above code are the <ul> and <script> tags.

We will be retrieving a list of products from our TakeShape project, then displaying their names and prices in a bulleted list. To populate the list, we've given it an id of resultsContainer, which we will reference later in our JavaScript.

You'll notice that the name of our script is takeshape-example.js, but you're free to name yours whatever you'd like. Be sure to specify the proper filepath to your script if it's not in the same directory as your index.html file, though.

Creating a JavaScript file

You can make your fetch request however you'd like, but for this example we'll use JavaScript's native fetch API. Since fetch returns a promise, we'll use async/await to interact with our request. That means we need to create an asynchronous function.

Rather than creating a named function, we'll use what's called an IIFE, which is just an anonymous function that gets called immediately. Study the code below:

takeshape-example.js
(async()=>{

})()

Now we'll make a fetch request to our API Endpoint, passing our API Key in the headers.

takeshape-example.js
try{
const result = await fetch(
'https://api.takeshape.io/project/6cdbcc52-5697-475b-872e-fcb6fd0e00d0/v3/graphql',
{
method: 'POST',
headers: {
'Authorization':'Bearer 6091d7bc2d8946e290486e1526483eda',
'Content-Type':'application/json'
},
body: JSON.stringify({
query: `query{
getProductList{
items{
_id
name
price
}
}
}`
})
}
)
} catch(error){
console.log("TakeShape query Error!", error)
}

In the above code, we're making a POST request to our project's GraphQL API. TakeShape expects the body of this request to have a property called query that takes a string with the query in it.

As you can see, our query is getProductList, and we want an _id, name and price for each product in the list. Now we just need the code for injecting this data into our <ul>.

Before the end of our try block, add the following:

takeshape-example.js
    const resultJSON = await result.json()

const containerList = document.getElementById('resultsContainer')

const {items} = resultJSON.data.getProductList

for(const product of items){
console.log(product)
const listItem = document.createElement('li')
const innerText = document.createTextNode(product.name + " : $" + product.price)
listItem.appendChild(innerText)
listItem.setAttribute('id', product._id)
containerList.appendChild(listItem)
}

In the above code, we're converting our result to JSON, then using a for ... of list to create <li> tags. We then insert the product's name and price into our <li>, and attach the product's _id property as an id.

The whole script should look like this:

takeshape-example.js
(async ()=> {
try{
const result = await fetch(
'https://api.takeshape.io/project/6cdbcc52-5697-475b-872e-fcb6fd0e00d0/v3/graphql',
{
method: 'POST',
headers: {
'Authorization':'Bearer 6091d7bc2d8946e290486e1526483eda',
'Content-Type':'application/json'
},
body: JSON.stringify({
query: `query{
getProductList{
items{
_id
name
price
}
}
}`
})
}
)

const resultJSON = await result.json()

const containerList = document.getElementById('resultsContainer')

const {items} = resultJSON.data.getProductList

for(const product of items){
console.log(product)
const listItem = document.createElement('li')
const innerText = document.createTextNode(product.name + " : $" + product.price)
listItem.appendChild(innerText)
listItem.setAttribute('id', product._id)
containerList.appendChild(listItem)
}
} catch(error) {
console.log("TakeShape fetch Error!", error)
}
})()

And you're done. The only thing left is to test it. You can open the index.html file in your favorite browser, or use a VS Code plugin like LiveServer to serve it on a local port. If you'd rather see it on a live site, create a repository in github and then deploy it to Netlify.

Here's what the page should look like:

And there you have it.

Still need help? Get in touch with us.