0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

google clone Part12 28 fetch data from google search api  取得したデータをブラウザで表示

Last updated at Posted at 2023-05-19

概要

目次

今回はGoogleのProgrammable SearchEngineを使って検索結果のデータを取得ブラウザ上に表示します。

cvzdfsaffdadfa.gif

開発環境

OS:Windows10
IDE:VSCode

"@next/font": "13.1.5",
"autoprefixer": "10.4.14",
"eslint": "8.39.0",
"eslint-config-next": "13.3.1",
"next": "13.3.1",
"postcss": "8.4.23",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.8.0",
"tailwindcss": "3.3.2"

実装のポイント

Programmable Search Engineを作成する

以下作成結果。黄色線部で使われている部分はAPIのパラメーターで使います。

image.png

APIキーの取得

Programmable Search EngineのドキュメントからAPIキーを取得します。

image.png

環境変数の設定

.env.localにAPI_KEYとCONTEXT_KEYを設定する
image.png

APIを叩いて検索結果のタイトルをブラウザに表示する

image.png

コード部分

app/search/web/page

page.jsx
export default async function WebSearchPage({searchParams}) {
  const response = await fetch(
    `https://www.googleapis.com/customsearch/v1?key=${process.env.API_KEY}&cx=${process.env.CONTEXT_KEY}&q=${searchParams.searchTerm}`
  );

  const data = await response.json();
  console.log(data);
  const results = data.items;
  return (
    <>{results && results.map((result) => <h1>{result.title}</h1>)}</>
  )
}

参考

API パラメーター

image.png

API レスポンス

image.png

image.png

その他

Udemy

githubコミット分

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?