LoginSignup
7
5

More than 5 years have passed since last update.

esa APIでCreate or Updateをする #esa_io #ruby

Posted at

esa APIを使って、

  • 新規記事なら登録
  • 登録済みなら更新

という処理を実装します。

前提

  • esa-ruby gem を利用
  • 環境変数の管理に dotenv gem を利用

※dotenvについては下記を参照

Ruby | dotenv gem で 環境変数をスマートに管理

esa APIの利用準備

  • esaのTEAMメニューを選択
  • 自ユーザーを選択
  • Personal access tokensタブを選択
  • Generate new tokenをクリック
  • Read / Write 双方にチェックをして Token description にAPIの用途を説明する内容を入力
  • Saveをクリック
  • tokenが表示されるので、内容を保存しておきます

プログラム

dotenv

# 利用準備で取得したtokenを設定
ESA_API_TOKEN=your token
TEAM=your team
require 'dotenv'
require 'esa'
Dotenv.load

name = '記事タイトル'
category = 'サンプル/カテゴリ'
# 検証用のためtrueにしてます。実際はfalseが良いです
wip = true

client = Esa::Client.new(access_token: ENV['ESA_API_TOKEN'], current_team: ENV['TEAM'])
response = client.posts(q: "name:#{name} category:#{category}")
if response.body['total_count'] == 0
  client.create_post(
    category: category,
    name: name,
    wip: wip,
    body_md: "なんか適当な本文"
  )
else
  post_number = response.body['posts'].first['number']
  client.update_post(post_number, body_md: body)
end

実用

こんな感じで必要になりました。
※リンク先に実際に実行した場合の画面キャプチャあり

DRYな画面一覧管理。プログラムから画面名を抽出し、esa APIで共有する

外部資料

7
5
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
7
5