Next.jsでブログ情報をAPI取得してみた

## この記事の目的
- Next.jsでブログを作成したときの備忘録
- Next.jsでAPI取得についての備忘録

## 概要
Next.jsでブログの側だけ作成したので、ダミーデータをプロジェクト内に用意し取得間で行ってみたのでまとめました
- ①デフォルトのAPI`pages/api/hello.ts`の動作確認
- ②ダミーデータ作成
- ③ダミーデータを取得してみる


## ①デフォルトのAPI`pages/api/hello.ts`の動作確認
デフォルトで作成されている`pages/api/hello.ts`の動作を確認していきます
`pages/api/hello.ts`が下記のようなJSONでnameプロパティに'John Doe'という文字列を含むオブジェクトを返す内容で用意されていたのでこちらの動作確認をしていきます
```pages/api/hello.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  re
```
次のURLでJSONでnameプロパティに'John Doe'という文字列を含むオブジェクトを返ってくるか確認していきます
```
http://localhost:3000/api/hello
```
下記の画像のようにオブジェクトが表示されればAPI取得が無事できていることが確認できます。
![スクリーンショット 2023-03-17 0.18.26.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/462658/a3267c77-7cda-4867-8ed1-1a4da7ecf45d.png)

## ②ダミーデータ作成
API取得対象のデータを`pages/api/data.tsx`ファイルを作成して書いていきます。
今回はJSONデータ内の「Trending」の中にブログ記事のデータを設定していきます。
<details><summary>pages/api/data.tsxにそのほかにもブログ記事のデータを追加したものをコードクリックして表示（こちらは今回の挙動確認には必要はないです）</summary><div>

```pages/api/data.tsx
export default {  
    Trending : [
        {
            id: 1,
            title: "API取得ブログタイトル(Trending)",
            subtitle: "サブタイトル",
            category: "ビジネス（カテゴリ）, 旅行（カテゴリ）",
            img : "/images/img1.jpg",
            description: `
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            `,
            published: "Jun 3,  2022",
            author: {
                name: "Pikimaru",
                img: "/images/author/author.jpeg",
                designation : "エンジニア"
            }
        },
        {
            id: 2,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/img2.jpg",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.
            `,
            published: "Jun 5,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 3,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/img3.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.
            `,
            published: "Jun 7,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 4,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/img4.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.
            `,
            published: "Jun 10,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 5,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/img5.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.
            `,
            published: "Jun 14,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        }
    ],
    Posts : [
        {
            id: 1,
            title: "API取得ブログタイトル(Posts)",
            subtitle: "サブタイトル",
            category: "ビジネス（カテゴリ）, 旅行（カテゴリ）",
            img : "/images/articles/posts/img1.jpg",
            description: `
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            `,
            published: "Jun 3,  2022",
            author: {
                name: "Pikimaru",
                img: "/images/author/author.jpeg",
                designation : "エンジニア"
            }
        },
        {
            id: 2,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/posts/img2.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, qui ea assumenda illo quidem 
            consequatur ducimus cum aliquam est minus provident placeat, nesciunt vitae. 
            Et aperiam magni non quasi est asperiores nobis atque suscipit incidunt dignissimos! Harum et sunt ea.

            When she reached the first hills of the Italic Mountains, she had a last view back on the skyline 
            of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, 
            the Line Lane. Pityful a rethoric question ran over her cheek, then she continued her way.

            Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.
            Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.

            A small river named Duden flows by their place and supplies it with the necessary regelialia. 
            It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
            `,
            published: "Jun 5,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 3,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/posts/img3.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, qui ea assumenda illo quidem 
            consequatur ducimus cum aliquam est minus provident placeat, nesciunt vitae. 
            Et aperiam magni non quasi est asperiores nobis atque suscipit incidunt dignissimos! Harum et sunt ea.

            When she reached the first hills of the Italic Mountains, she had a last view back on the skyline 
            of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, 
            the Line Lane. Pityful a rethoric question ran over her cheek, then she continued her way.

            Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.
            Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.

            A small river named Duden flows by their place and supplies it with the necessary regelialia. 
            It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
            `,
            published: "Jun 7,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 4,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/posts/img4.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, qui ea assumenda illo quidem 
            consequatur ducimus cum aliquam est minus provident placeat, nesciunt vitae. 
            Et aperiam magni non quasi est asperiores nobis atque suscipit incidunt dignissimos! Harum et sunt ea.

            When she reached the first hills of the Italic Mountains, she had a last view back on the skyline 
            of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, 
            the Line Lane. Pityful a rethoric question ran over her cheek, then she continued her way.

            Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.
            Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.

            A small river named Duden flows by their place and supplies it with the necessary regelialia. 
            It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
            `,
            published: "Jun 10,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 5,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/posts/img5.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, qui ea assumenda illo quidem 
            consequatur ducimus cum aliquam est minus provident placeat, nesciunt vitae. 
            Et aperiam magni non quasi est asperiores nobis atque suscipit incidunt dignissimos! Harum et sunt ea.

            When she reached the first hills of the Italic Mountains, she had a last view back on the skyline 
            of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, 
            the Line Lane. Pityful a rethoric question ran over her cheek, then she continued her way.

            Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.
            Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.

            A small river named Duden flows by their place and supplies it with the necessary regelialia. 
            It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
            `,
            published: "Jun 14,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 6,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/posts/img2.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind 
            text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, qui ea assumenda illo quidem 
            consequatur ducimus cum aliquam est minus provident placeat, nesciunt vitae. 
            Et aperiam magni non quasi est asperiores nobis atque suscipit incidunt dignissimos! Harum et sunt ea.

            When she reached the first hills of the Italic Mountains, she had a last view back on the skyline 
            of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, 
            the Line Lane. Pityful a rethoric question ran over her cheek, then she continued her way.

            Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.
            Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.

            A small river named Duden flows by their place and supplies it with the necessary regelialia. 
            It is a paradisematic country, in which roasted parts of sentences fly into your mouth.
            `,
            published: "Jun 5,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
    ],
    Popular : [
        {
            id: 1,
            title: "API取得ブログタイトル(Popular)",
            subtitle: "サブタイトル",
            category: "ビジネス（カテゴリ）, 旅行（カテゴリ）",
            img : "/images/articles/img1.jpg",
            description: `
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            `,
            published: "Jun 3,  2022",
            author: {
                name: "Pikimaru",
                img: "/images/author/author.jpeg",
                designation : "エンジニア"
            }
        },
        {
            id: 2,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/img2.jpg",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic
            far World of Grammar.
            `,
            published: "Jun 5,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 3,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/img3.jpg",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic
            far World of Grammar.
            `,
            published: "Jun 7,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 4,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/img4.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic
            far World of Grammar.
            `,
            published: "Jun 10,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        },
        {
            id: 5,
            title: "Your most unhappy customers are your greatest source of learning",
            subtitle: "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.",
            category: "Business, Travel",
            img : "/images/articles/img5.png",
            description: `
            Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic
            far World of Grammar.
            `,
            published: "Jun 14,  2022",
            author: {
                name: "Flying High",
                img: "/images/author/author1.jpg",
                designation : "CEO and Founder"
            }
        }
    ]
}

```
</div></details>

```pages/api/data.tsx
export default {  
    Trending : [
        {
            id: 1,
            title: "API取得ブログタイトル(Trending)",
            subtitle: "サブタイトル",
            category: "ビジネス（カテゴリ）, 旅行（カテゴリ）",
            img : "/images/img1.jpg",
            description: `
            ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ブログコンテンツテキスト＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
            `,
            published: "Jun 3,  2022",
            author: {
                name: "Pikimaru",
                img: "/images/author/author.jpeg",
                designation : "エンジニア"
            }
        }
    ]
}
```


## ③ダミーデータを取得してみる
②で作成した`pages/api/data.tsx`をインポートし作成したデータの`Trending`だけ取得しJSON型で返す関数を`pages/api/trending.tsx`を作成し記載していきます。
```pages/api/trending.tsx
// Next.jsから提供される、APIリクエストを表す型
import { NextApiRequest, NextApiResponse } from 'next';

// ダミーデータをインポート
import data from './data';

// APIのリクエストハンドラー関数
export default function handler(req: NextApiRequest, res: NextApiResponse){
    // ダミーデータからTrendingを取得
    const { Trending } = data;

    // Trendingが存在する場合は、HTTPステータスコード200を返し、TrendingデータをJSONで返す
    if(Trending) return res.status(200).json(Trending);

    // Trendingが存在しない場合は、HTTPステータスコード404を返し、エラーメッセージを含むJSONを返す
    return res.status(404).json({ error: "Data Not Found"});
}
```
これでデータを取得できるようになったので実際の画面で取得できているか確認していきます
`pages/api/trending.tsx`に書いたので`http://localhost:3000/api/trending`をURLで叩くとデータの中の`Trending`の内容がJSON型で帰ってきているかと思います
![スクリーンショット 2023-03-17 23.18.02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/462658/3b89fc53-64a3-0245-e681-95e6a2fb3f3d.png)


## まとめ
ダミーデータを使用してAPI取得のテストとしてみました。
階層も関数もわかりやすくて、まず側だけ作る際はいいなと思いました。
側が全部できたらmicroCMSと連携していきたい、、