Beer API fetching with RapidAPI and NextJS

Beer API fetching with RapidAPI and NextJS

Uen's
·Feb 21, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

I was curious about integrating rapidapi with Nextjs. And Success with trying beer api in rapidapi with next js. First of all install next js app with this command.

npx create-next-app beers

after nextjs installation finish install axios package with this command

npm install axios

and create folder utils and inside create fetchApi.js file to for us to fetch data from rapid API. And add following code to fetchApi.js

import axios from "axios"
export const baseUrl = "https://beer-live.p.rapidapi.com"

export const fetchApi = async (url) => {
  const { data } = await axios.get(url, {
    headers: {
      "x-rapidapi-host": "beer-live.p.rapidapi.com",
      "x-rapidapi-key": "YOUR_RAPID_API_KEY",
    },
  })
  return data
}

You can add your rapid api key from here

After adding fetch api you can now start to call. First we will create a components folder inside root of nextjs app. And we will create a Beers.jsx file inside the components folder. And will add this code

const Beer = ({ beer: { title, ort } }) => {
  return (
    <>
      <tbody>
        <tr>
          <td>{title}</td>
          <td>{ort}</td>
        </tr>
      </tbody>
    </>
  )
}

export default Beer

now we can call our api from pages/index.js like this

import { baseUrl, fetchApi } from "../utils/fetchApi"
import Beer from "../components/Beer"
export default function Home({ beersHessen }) {
  return (
    <>
      <div>
        <h1>Home</h1>
        <table>
          <thead>
            <tr>
              <th>Name of Beer</th>
              <th>City</th>
            </tr>
          </thead>
          {beersHessen.map((beer) => (
            <Beer beer={beer} key={beer.id} />
          ))}
        </table>
      </div>
    </>
  )
}

export async function getStaticProps() {
  const beersHessen = await fetchApi(`${baseUrl}/brews/hessen`)

  return {
    props: {
      beersHessen,
    },
  }
}

We have fetched data from rapidapi. Beers from hessen state I choose. According to beers api documentation.

Here is a github repo with beers top example too. Feel free to use as you wish. And Please do not forget to give a star on github repo.

 
Share this