Skip to main content

Use TakeShape with Gridsome

Gridsome is a fantastic static site generator for users who want to integrate content pulled from a GraphQL API into their static site's build process. TakeShape is a fantastic tool for generating a single GraphQL API from different data sources. They're a perfect match!

In this doc, we'll show you how to integrate TakeShape with Gridsome.

The first step will be creating a project; you need a API Endpoint and API Key in order to connect TakeShape to your Gridsome project. Follow our guide to learn how to create a project. Already have one? Continue below to connect it to your Gridsome project!

Getting your project information#

You'll need to generate an API Key for your project. Check out our docs that describe that process.

You can find your project’s API Endpoint in the "Useful Snippets" section of your project's dashboard in the TakeShape web client. Open your project in the web client, then click the Home tab. Now scroll down, and in the bottom left you'll see a section titled "Useful Snippets". Copy your API Endpoint from there!

Connecting your project#

Once you have your API Endpoint, and have access to an API Key with dev permissions (see our API Key docs for more information), then you're ready to start!

Gridsome has a powerful <page-query> component that allows you to add GraphQL queries directly into your page components. You can then display whatever data you pull from the API, and this can all be done at build time.

Let's get started!

Protecting your project information#

To keep your API Endpoint and API key safe, it's best to use environment variables.

Install the dotenv node package to use environment variables in the build script you'll be making. Go to the terminal in your project directory and enter npm i dotenv.

Now in the root of your project directory, create a file called .env.

Inside, you will define your API Key and API Endpoint as variables:

.env
API_ENDPOINT=YourEndpointHereAPI_KEY=YourApiKeyHere

Now you can use this data in your Gridsome build process without risk of exposing it to the public.

Creating a Gridsome Project#

If you don't have a Gridsome project already, you can get started quickly by using TakeShape's Gridsome Starter repo. The starter repo includes all the code used in this doc.

Otherwise, let's get started! Install gridsome with the below command in your terminal:

npm install --global @gridsome/cli

Now navigate to a folder where you'd like to store your project directory, and enter the following command:

gridsome create my-gridsome-project

Open your newly-created project directory in your favorite IDE, or change directories into it.

Creating your Gridsome Server file#

To get started, you'll need to add a file called gridsome.server.js to the root of your project.

This file exports a function that fetches data from your TakeShape API. Your TakeShape data will then be added to the build process for your site. For now, we'll just export an empty function:

gridsome.server.js
module.exports = function(api) {    //Our query code will go here}

At the top of the module, we'll add the code required to configure dotenv, so we have access to environement variables. We'll also add the node-fetch library, which we'll need to request data from our TakeShape project.

If you don't already have node-fetch installed, simply enter npm i node-fetch into your terminal. The code for requiring both of these packages is below

gridsome.server.js
require('dotenv').config()const fetch = require('node-fetch')
module.exports = function(api) {    //Our query code will go here}

In order to add the data fetched from TakeShape to your project, we need to use the api.loadSource() hook from Gridsome's Server API.

Within that hook, you'll create a 'collection', which is just a Gridsome data structure that represents the data you'll be collecting from TakeShape. In this example, we want a list of products from an ecommerce API.

So let's create a collection called ProductList, and keep it in an object called products.

gridsome.server.js
module.exports = function(api) {    api.loadSource(async actions => {        const products = actions.addCollection('ProductList')    })}

Once you have a variable to hold your newly-created collection, it's time to do a fetch request to your TakeShape project's GraphQL API. Your API endpoint will be of this format:

https://api.takeshape.io/project/YOUR-PROJECT-ID/v3/graphql

You'll use your API Key as a Bearer Token for authorization. See the code below for a detailed example:

gridsome.server.js
module.exports = function(api) {    api.loadSource(async actions => {        const products = actions.addCollection('ProductList')
        const result = await fetch(process.env.API_ENDPOINT, {        method: "POST",        headers: {            "Content-Type": "application/json",            Authorization: `Bearer ${process.env.API_KEY}`,            accept: "application/json",        },        body: JSON.stringify({            query: `query {                getProductList {                    items {                        _id                        name                        price                    }                }            }`,        }),        });
        const resultJSON = await result.json();    })}

In the above code, you may have noticed that in the body of the fetch request, the main property is query. This is the property TakeShape uses to read your GraphQL query.

Your query must already be defined in your schema. Read our Schema docs for more information. In this example, we just want the name and price of every item in our product list.

After converting the result of your query to json as shown above, the final step will be to add a for ... of loop that cycles through all the items returned from TakeShape, and converts them into nodes in your ProductList collection.

After converting your fetch result to json as shown above, add the below code to your api.loadSource() hook:

gridsome.server.js
    const resultJSON = await result.json();
    for (const item of resultJSON.data.getProductList.items){      products.addNode({        _id: item._id,        name: item.name,        description: item.price,      })    }

And you're all connected! You can access your TakeShape data with Gridsome's Page API! Read on to learn more about how to pull that data into your Gridsome components. Below you'll find the full gridsome.server.js script for this example:

require('dotenv').config()const fetch = require('node-fetch')
module.exports = function(api) {  api.loadSource(async actions => {
    const products = actions.addCollection('ProductList')
    const result = await fetch(process.env.API_ENDPOINT, {      method: "POST",      headers: {        "Content-Type": "application/json",        Authorization: `Bearer ${process.env.API_KEY}`,        accept: "application/json",      },      body: JSON.stringify({        query: `query {              getProductList {                items {                  _id                  name                  price                }              }            }`,      }),    });
    const resultJSON = await result.json();
    for (const item of resultJSON.data.getProductList.items){      products.addNode({        _id: item._id,        name: item.name,        price: item.price,      })    }  })}

Adding your TakeShape data to your Gridsome components#

Gridsome allows you to make GraphQL queries from within your page components using the <page-query> tags. Below is an example of how you could query your data from within a component using <page-query>:

index.vue
<page-query>  query {    products: allProductList {      edges {        node {          _id          name          price        }      }    }  }</page-query>

The above code executes the allProductList query, then assigns what it returns to products. The edges and node properties give us access to the data we specified in our query to TakeShape back in the gridsome.server.js file.

The method is called allProductList because that's the query name Gridsome automatically generates. If your collection is called ProductList, then to query all items within it, you must call allProductList. If you collections was called ExampleQuery, you would call allExampleQuery. To learn more, check out the gridsome docs.

Finally, to access your data, you'll find it in Gridsome's $page object. Here's how you would render divs for every item you received from TakeShape, filling them out with your product information.

index.vue
<template>  <div>    <h1>Products</h1>    <div v-for="edge in $page.products.edges" :key="edge.node._id">      <p>        <b>{{ edge.node.name }}</b>        <span>{{ edge.node.price }}</span>      </p>    </div>  </div></template>

In the above code, each item pulled from TakeShape is represented as an edge. The node property gives us access to that edge's data, and we can reference the properties we defined in our gridsome.server.js script.

For more information, read about Gridsome GraphQL queries in their docs.

Here's the final index.vue file.

index.vue
<template>  <div>    <h1>Products</h1>    <div v-for="edge in $page.products.edges" :key="edge.node._id">      <p>        <b>{{ edge.node.name }}</b>        <span>{{ edge.node.price }}</span>      </p>    </div>  </div></template>
<page-query>  query {    products: allProductList {      edges {        node {          name          _id          price        }      }    }  }</page-query>
<script>import { Pager } from 'gridsome';import PostSummary from '~/components/PostSummary.vue'export default {  components: {    Pager,    PostSummary  }}</script>

Just enter npm run develop to start your project!

And here's what the page should look like after you run it:

You're all set#

And that's it! You're ready to incorporate TakeShape into your Gridsome process!

Still confused? Ask for help!