
今回はNext.jsを使ってAPIエンドポイントを作成し、GET Requestを扱う方法について紹介します。
環境構築
まずは新しいプロジェクトを作成します。今回は「next-api」というプロジェクト名にしました。
プロジェクトの作成の仕方は以下の記事を参考にどうぞ。
プロジェクトディレクトリに移動したら、下記3つのファイル・ディレクトリを削除します。
- pages/api
- pages/index.js
- styles/Home.module.css
Terminal
rm -r pages/api
rm -r pages/index.js
rm -r styles/Home.module.css
Next.jsのAPIルーティングをやってみる
Next.jsでAPIルーティングを行うためには、pagesディレクトリ直下にapiディレクトリを用意する必要があります。pages/apiディレクトリ以下のファイル・フォルダ構成が/api/xxxxのようにマップされ、ページとしてではなくAPIエンドポイントとして扱われます。
apiディレクトリを作成したら、その中にindex.jsファイルを作成して、リクエストがあったら{name: 'John Doe'}とレスポンスするコードを記述していきます。
Terminal
mkdir pages/api
touch pages/api/index.js
pages/api/index.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe'})
}
結果
apiエンドポイントを作成するには、当該関数にreqとresという2つの引数を持たせなければなりません。resはクライアントに対するresponse(応答)の処理を行う場合、reqはデータベースなどに対するrequest(要求)の処理を行う場合に使用されます。
apiディレクトリの中の構造は、エンドポイントのURL(パス)に対応します。
- api/index.js→/api
- api/recent.js→/api/recent
- api/blog/index.js→api/blog
- api/blog/recent.js→api/blog/recent
Next.jsのAPIエンドポイントから一覧データを取得・表示する(GET Request)
続いては、作成したAPIエンドポイントからデータを取得・表示するところまでやってみたいと思います。
まずはapiディレクトリ直下にcommentsディレクトリを作成し、その中にindex.jsファイルを作成します。さらに、pagesディレクトリ直下にcommentsディレクトリを作成し、その中にもindex.jsファイルを作成します。
apiディレクトリ直下に作成したものがエンドポイント用、pagesディレクトリ直下に作成したものが表示用です。
Terminal
mkdir pages/api/comments
touch pages/api/comments/index.js
mkdir pages/comments
touch pages/comments/index.js
pages/api/comments/index.js
export const comments = [
{
id: 1,
text: "This is the first comment",
},
{
id: 2,
text: "This is the second comment",
},
{
id: 3,
text: "This is the third comment",
},
]
pages/comments/index.js
import {useState} from 'react'
function CommentsPage() {
const [comments, setComments] = useState([])
const fetchComments = async () => {
const response = await fetch('/api/comments')
const data = await response.json()
setComments(data)
}
return(
<>
<button onClick={fetchComments}>Load comments</button>
{
comments.map(comment => {
return (
<div key={comment.id}>
{comment.id} {comment.text}
</div>
)
})
}
</>
)
}
export default CommentsPage
結果
まとめ
次はAPI POST Requestを扱う方法について紹介します。