Wednesday, 3 March, 2021 UTC


Summary

More often than not, when building your JavaScript application, you’ll want to fetch data from a remote source or consume an API. There’s lots of cool stuff that can be done with data from a range of publicly available APIs.
With Vue.js, you can literally build an app around one of these services and start serving content to users in minutes.
I’ll demonstrate how to build a simple news app that will show the top news articles of the day, and that will allow users to filter by their category of interest, fetching data from the New York Times API. You can find the complete code for this tutorial here.
Here’s what the final app will look like:
To follow along with this tutorial, you’ll need Node.js and (optionally) Yarn installed on your machine. To install Node, you can either head to the official download page and grab the Node binaries for your system, or use a version manager instead.
Once Node is installed, to pull in Yarn, run:
npm i -g yarn
You’ll also require a basic knowledge of Vue.js. You can find a great getting started guide for that here.
Acquire an API Key
To make use of the NYTimes API, you’ll need to get an API key. So if you don’t already have one, head over to their signup page and register to get an API key for the Top Stories API.
We’ll be using the top stories API endpoint to fetch data from. Take note that there are multiple sections such as “home”, “travel”, “arts” and “science” that this API provides. We’ll need to build a filter that can allow users to select a section and load the stories within it.
Below are example calls:
https://api.nytimes.com/svc/topstories/v2/arts.json?api-key=yourkey
https://api.nytimes.com/svc/topstories/v2/home.json?api-key=yourkey
https://api.nytimes.com/svc/topstories/v2/science.json?api-key=yourkey
https://api.nytimes.com/svc/topstories/v2/us.json?api-key=yourkey
https://api.nytimes.com/svc/topstories/v2/world.json?api-key=yourkey
Feel free to use your favorite REST client (such as Hoppscotch or Insomnia) to test your API calls.
Project Structure
Let’s quickly spin up a Vue 3 project using Vite, a dev server that runs faster than Vue CLI:
yarn create @vitejs/app vue-news-app --template vue

# Install package dependencies
cd vue-news-app
yarn install

# Confirm app can run
yarn dev
Open localhost:3000 in your browser. You should have the following view:
Next, let’s install the TailwindCSS framework to provide some basic styling. You’ll need to stop the server in order to perform this action:
yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest

# Generate tailwind.config.js and postcss.config.js files
npx tailwindcss init -p
We’ll need some additional package utilities to help us format dates and clamp the number of lines for the abstract field:
yarn add @tailwindcss/line-clamp date-fns
@tailwindcss/line-clamp is a plugin that needs to be included in tailwind.config.js. Below is the full configuration:
module.exports = {
  purge: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [require("@tailwindcss/line-clamp")],
}
Next, create an index.css file in the src folder and add this code:
@tailwind base;
@tailwind components;
@tailwind utilities;

body {
  @apply antialiased text-green-900 bg-green-50;
  font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
}

#app {
  @apply flex flex-col min-h-screen overflow-x-hidden;
}
In addition to importing the required Tailwind CSS classes, we’ve included a few CSS settings to help us define the default theme of our application. We’ve also implemented a flex layout system to help us create a sticky header and footer for our application.
We’ll need to import index.css in src/main.js:
import { createApp } from "vue"
import App from "./App.vue"
import "./index.css"

createApp(App).mount("#app")
Let’s now go ahead and define our application layout. First, clear out any existing components in src/components. Next, within the same folder, create these three files:
  • Layout.vue
  • Header.vue
  • Footer.vue
Copy the following code for each file:
src/components/Footer.vue:
<template>
  <footer
    class="px-4 py-8 text-sm font-bold text-center text-green-100 bg-green-900">
    <p class="text-sm tracking-wide">Copyright (c) 2021 SitePoint</p>
  </footer>
</template>
src/components/Header.vue:
<template>
  <header class="flex justify-center py-6 bg-green-900 place-items-center">
    <img alt="Vue logo" src="../assets/logo.png" width="32" />
    <span class="ml-4 text-lg font-bold text-green-100 md:text-xl">
      Vue News | NYTimes Edition
    </span>
  </header>
</template>
src/components/Layout.vue:
<template>
  <Header />
  <main class="container flex-grow px-4 mx-auto my-12">
    <slot />
  </main>
  <Footer />
</template>

<script>
import Header from "./Header.vue"
import Footer from "./Footer.vue"

export default {
  components: {
    Header,
    Footer,
  },
}
</script>
Finally, update src/App.vue:
<template>
  <Layout>
    <p>Main content goes here</p>
  </Layout>
</template>

<script>
import Layout from "./components/Layout.vue"

export default {
  components: {
    Layout,
  },
}
</script>
Execute yarn dev. The browser should refresh automatically.
With the application layout completed, we can now start building the core logic of our news app.
Continue reading Fetching Data from a Third-party API with Vue.js and Axios on SitePoint.