iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍤

Building an Unofficial Zenn Trending API with Netlify Functions

に公開

If you just want to use the API, please check the following links:

https://zenn-api.netlify.app/trendTech.json
https://zenn-api.netlify.app/trendIdea.json
https://zenn-api.netlify.app/trendBook.json

These correspond to the trends for Tech, Ideas, and Books, respectively. (In case the data is not being fetched correctly, please let me know in the comments section or via an Issue in the repository.)

Background

I did the same thing on Qiita over a year ago.

https://qiita.com/HelloRusk/items/803f9599cde72810f1a8

This article received more response than I expected, and the API was even used in personal development projects.

https://qiita.com/cryptobox/items/844cd3686dcbcd93e7f2

For that reason, I decided to set up a URL for Zenn as well that can return JSON directly.

Netlify Functions

This is a service that allows you to use AWS Lambda on Netlify.
The free tier allows up to 125,000 requests/month and 100 hours of runtime/month (as of December 2019), which is more than enough for a hobby project.

I think Vercel might be more convenient nowadays, though...

How It's Used

It simply uses axios to GET the URL and cheerio to parse it.

src/lambda/trendTech.ts
import axios from 'axios'
import cheerio from 'cheerio'

const fetchTrend = (html: string) => {
  const $ = cheerio.load(html)
  const raw = $('script[id=__NEXT_DATA__]').html() ?? ''
  if (raw === undefined) return {}
  const rawData = JSON.parse(raw).props.pageProps.dailyTechArticles

  return rawData
}

export const handler = async () => {
  const url = 'https://zenn.dev/'

  return await axios
    .get(url)
    .then(({ data }) => {
      return {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify(fetchTrend(data)),
      }
    })
    .catch(err => {
      return {
        statusCode: 500,
        body: err,
      }
    })
}

For more details, please check the repository:

https://github.com/kaisugi/zenn-trend-api

Discussion