Tutorial

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

Published on February 20, 2020
author

John Au-Yeung

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

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 our products

About the authors
Default avatar
John Au-Yeung

author

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.

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!

Become a contributor for community

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

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.