LoginSignup
0
0

webhookとweb APIについて浅く理解する

Posted at

この記事を読んでわかること

webhookとAPIの違いについてなんとなく理解できるかも..?

API

クライアント(ユーザーのブラウザやアプリケーション)がTwitterのAPIエンドポイントにリクエストを送信します。
Twitterのサーバーがそのリクエストを受け取り、即座にレスポンスを返します。

コード例(Twitter APIから最新のツイートを取得):

require 'twitter'

client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "YOUR_CONSUMER_KEY"
  config.consumer_secret     = "YOUR_CONSUMER_SECRET"
  config.access_token        = "YOUR_ACCESS_TOKEN"
  config.access_token_secret = "YOUR_ACCESS_SECRET"
end

tweets = client.user_timeline('twitter_user')
puts tweets.first.text
[クライアント] ------> [Twitter API エンドポイント] -----> [Twitter サーバー] -----> [クライアント]
    リクエスト          リクエストを処理してレスポンスを返す            レスポンス
                   イベントのデータ                   イベントの処理

Webhook

Twitterのサーバーが特定のユーザーが新しいツイートを投稿したときに、あらかじめ設定されたWebhookエンドポイントに通知を送信します。
クライアント側のWebhookエンドポイントはその通知を受け取り、対応する処理を実行します。

コード例(RailsでWebhookを受け取るエンドポイントを設定):

# config/routes.rb

Rails.application.routes.draw do
  # Webhookを受け取るエンドポイントを定義
  post '/twitter/webhook', to: 'twitter_webhook#receive'
end

# app/controllers/twitter_webhook_controller.rb

class TwitterWebhookController < ApplicationController
  skip_before_action :verify_authenticity_token

  def receive
    # Webhookからのデータを処理する
    webhook_data = JSON.parse(request.body.read)
    
    # 特定の処理を実行する(例:新しいツイートがあった場合)
    if webhook_data['event'] == 'tweet'
      tweet_text = webhook_data['data']['text']
      puts "New tweet: #{tweet_text}"
    end

    # 応答を返す
    head :ok
  end
end
[Twitter サーバー] -------> [Webhook エンドポイント] -------> [クライアント]
      イベント通知                       イベントのデータ                   イベントの処理

まとめ

このように、APIはクライアントがリクエストを送信し、サーバーが即座にレスポンスを返すのに対して、Webhookはサーバーがイベントが発生したときにクライアントに通知を送信し、クライアントがその通知を受け取って対応する処理を実行する仕組みです。

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