Tutorial

Creating a Static Site with Gridsome and a REST API Data Source

Published on February 20, 2020
Default avatar

By John Au-Yeung

Creating a Static Site with Gridsome and a REST API Data Source

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this article, we’ll look at how to create a static website using Gridsome, a static site generator that’s based on Vue.js and GraphQL and resembles Gatsby.js in many ways feature-wise. We’ll build a simple site with Gridsome that gets data from a REST API data source.

We’ll get the data from this News API.

Getting Started

To get started, we have to install the Gridsome CLI to create our project. To do this, we run:

$ npm install --global @gridsome/cli

or with Yarn:

$ yarn global add @gridsome/cli

Then we create our Gridsome site by running:

$ gridsome create news-site

Then we go to our news-site directory and run gridsome develop. Next, we open up our new Gridsome project in the browser by going to http://localhost:8080.

Getting Data from a REST API

To get data from a REST API, first we have to add the Axios HTTP client by running:

$ npm i axios

Next, we create a .env file and then add our API key to access the News API:

GRIDSOME_NEWS_API_KEY=your_api_key

Replace your_api_key with your own key that you got from the News API website.

Then we can add the code to retrieve the data from into gridsome.server.js file as follows:

gridsome.server.js
const axios = require('axios')

module.exports = function (api) {
  api.loadSource(async actions => {
    const { data } = await axios.get(`
      http://newsapi.org/v2/top-headlines?country=us&apiKey=${process.env.GRIDSOME_NEWS_API_KEY}`)
    const collection = actions.addCollection({
      typeName: 'Posts'
    })

    for (const item of data.articles) {
      collection.addNode({
        content: item.content,
        title: item.title
      })
    }
  })
}

The code above gets the data from the API and then adds them to a collection so we can get them in any Vue component.

The environment variables from .env are loaded into process.env as a property.

After we change the code, we have to restart the app for the changes in gridsome.server.js to take effect. This is because the fetching is done when the project loads.

Then in index.vue, we change the existing code to:

index.vue
<template>
  <div>
    <div v-for="edge in $page.allPosts.edges" :key="edge.node.title">
      <h1 v-html="edge.node.title" />
      <div v-html="edge.node.content"></div>
    </div>
  </div>
</template>

<page-query>
query {
  allPosts {
    edges {
      node {
        content
        title
      }
    }
  }
}
</page-query>

Here’s the shape of the returned results from the GraphQL query:

query {
  allPosts {
    edges {
      node {
        content
        title
      }
    }
  }
}

And that’s available in the template so we can just loop through the items as they’re returned from the Gridsome GraphQL API.

If you want to test the query in the GraphQL sandbox, we can go to http://localhost:8080/___explore and then make the same query in the page-query section and check the results.

Then when we go back to http://localhost:8080/, we get the title and content from the News API as we’ve added the items in gridsome.server.js.

We just use the normal v-for for rendering items from the array and v-html to display the raw HTML content from the API data.

Conclusion

As you saw, we can easily get data from a REST API with Gridsome and Axios. The data is fetched when the project loads. Once we fetched the data, we can retrieve them from Gridsome’s own GraphQL API so we can display the items in our template. ✨

Here are 3 more articles you might like if you’re interested in learning more about Gridsome:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
John Au-Yeung

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel