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?

ホットペッパーグルメサーチAPI活用ガイド:PythonとFastAPIで作るレストラン検索

Posted at

概要

ここでは、リクルートが提供する「ホットペッパーグルメサーチAPI」を使って、Pythonを使いレストラン情報を取得する方法を解説します。 また、実際のコード例として、FastAPIを使ったバックエンド側の実装も紹介しようと思います。


ホットペッパーグルメサーチAPIとは?

ホットペッパーグルメに掲載されている飲食店の情報を、エリア、ジャンル、予算などの条件で検索できるAPIです。 利用するには、リクルートWEBサービスの利用登録(無料)を行い、APIキーを取得する必要があります。


APIの基本仕様

  • エンドポイントhttps://webservice.recruit.co.jp/hotpepper/gourmet/v1/
  • レスポンス形式: XML / JSON (パラメータで指定可能)

主なリクエストパラメータ

パラメータ名 説明
key APIキー YOUR_API_KEY
format レスポンス形式 (

json or xml)
json
genre ジャンルコード G001 (居酒屋)
large_area 大エリアコード Z011 (東京)
budget 予算コード B002 (2001~3000円)
count 取得件数 50

3. Pythonでの実装例 (Requests)

まずは、シンプルに requests ライブラリを使ってデータを取得してみようと思います。

import requests

def get_restaurants(api_key, genre=None, area=None):

    url = "https://webservice.recruit.co.jp/hotpepper/gourmet/v1/"

    params = {

        "key": api_key,

        "format": "json",

        "count": 10

    }

    if genre:

        params["genre"] = genre

    if area:

        params["large_area"] = area

    try:

        response = requests.get(url, params=params)

        response.raise_for_status()

        data = response.json()

        shops = data["results"]["shop"]

        for shop in shops:

            print(f"店名: {shop['name']}")

            print(f"アクセス: {shop['access']}")

            print("-" * 20)

    except requests.exceptions.RequestException as e:

        print(f"エラーが発生しました!!!: {e}")

# 使用例
API_KEY = "YOUR_API_KEY" # 取得したAPIキーを設定
get_restaurants(API_KEY, genre="G001", area="Z011")

4. FastAPIでのバックエンド実装例

次に、このAPIをラップして、フロントエンドから使いやすくするためのAPIサーバーをFastAPIで構築してみます。

ディレクトリ構成

backend/

  ├── main.py

  └── requirements.txt

必要なライブラリ

pip install fastapi uvicorn requests

main.py の実装

from fastapi import FastAPI, Query

from fastapi.middleware.cors import CORSMiddleware

import requests

import os

app = FastAPI()

# CORS設定 (フロントエンドからのアクセスを許可)

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],

    allow_methods=["*"],

    allow_headers=["*"],

)

API_KEY = os.environ.get("HOTPEPPER_API_KEY", "YOUR_API_KEY")

@app.get("/api/search")

async def search_restaurant(

    genre: str = Query(None),

    large_area: str = Query(None),

    budget: str = Query(None)

):

    url = "https://webservice.recruit.co.jp/hotpepper/gourmet/v1/"

    params = {

        "key": API_KEY,

        "format": "json",

        "count": 20

    }

    if genre:

        params["genre"] = genre

    if large_area:

        params["large_area"] = large_area

    if budget:

        params["budget"] = budget

    try:

        response = requests.get(url, params=params)

        response.raise_for_status()

        data = response.json()

        return data["results"]["shop"]

    except Exception as e:

        return {"error": str(e)}

if __name__ == "__main__":

    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

5. マスタデータの活用

検索条件(ジャンルやエリア)を指定させるには、他のマスタAPIも活用すると便利かと思います。

  • ジャンルマスタhttps://webservice.recruit.co.jp/hotpepper/genre/v1/
  • エリアマスタhttps://webservice.recruit.co.jp/hotpepper/large_area/v1/

まとめ

ホットペッパーグルメサーチAPIを使うことで、飲食店データ取得し、 個人開発のグルメアプリや、チャットボットの機能拡張など、様々なシーンで活用できると思います。またapi辞退も非常に使用しやすい設計になっているので ぜひ試してみてください!

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?