サンプルコード

curl・Node.js・Python で、画像のアップロード、記事のアップサート、公開までの流れをまとめた例です。

「画像をアップロード → 記事を作成(アップサート)→ 下書きなら公開」の流れを言語ごとにまとめました。キーは環境変数 WEEKERP_API_KEY に保存している前提です。

 

curl

BASE=https://api-open.weekerp.com/blog/v1
AUTH="Authorization: Bearer $WEEKERP_API_KEY"

# 1) 画像
COVER=$(curl -s -X POST "$BASE/uploads" -H "$AUTH" -F "file=@cover.png" | jq -r .url)

# 2) 記事(あれば更新、なければ作成)
POST_ID=$(curl -s -X PUT "$BASE/posts/external/prod-123" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d "{\"lang\":\"ja\",\"slug\":\"product-123-review\",\"title\":\"商品123のレビュー\",
       \"thumbnail\":\"$COVER\",\"content\":\"# 商品123\\n\\n![表紙]($COVER)\"}" | jq -r .id)

# 3) 公開
curl -s -X POST "$BASE/posts/$POST_ID/publish" -H "$AUTH" | jq .status

 

Node.js(18 以上、fetch)

import { readFile } from 'node:fs/promises';

const BASE = 'https://api-open.weekerp.com/blog/v1';
const headers = { Authorization: `Bearer ${process.env.WEEKERP_API_KEY}` };

async function call(method, path, body) {
  const res = await fetch(`${BASE}${path}`, {
    method,
    headers: body instanceof FormData ? headers : { ...headers, 'Content-Type': 'application/json' },
    body: body === undefined || body instanceof FormData ? body : JSON.stringify(body),
  });
  if (res.status === 204) return null;
  const data = await res.json();
  if (!res.ok) {
    // message ではなく code で分けます
    const err = new Error(`${data.error.code}: ${data.error.message}`);
    err.code = data.error.code;
    err.retryAfter = Number(res.headers.get('Retry-After')) || undefined;
    throw err;
  }
  return { status: res.status, data };
}

// 1) 画像
const form = new FormData();
form.append('file', new Blob([await readFile('cover.png')], { type: 'image/png' }), 'cover.png');
const { data: cover } = await call('POST', '/uploads', form);

// 2) 記事(アップサート)
const { status, data: post } = await call('PUT', '/posts/external/prod-123', {
  lang: 'ja',
  slug: 'product-123-review',
  title: '商品123のレビュー',
  thumbnail: cover.url,
  content: `# 商品123\n\n![表紙](${cover.url})`,
  categories: ['review'],
});
console.log(status === 201 ? '作成' : '更新', post.id);

// 3) 下書きのときだけ公開
if (post.status === 'draft') {
  const { data: published } = await call('POST', `/posts/${post.id}/publish`);
  console.log(published.status); // "published"
}

 

Python(requests)

import os
import time
import requests

BASE = "https://api-open.weekerp.com/blog/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['WEEKERP_API_KEY']}"


def call(method, path, **kwargs):
    for _ in range(3):
        res = session.request(method, BASE + path, timeout=60, **kwargs)
        if res.status_code == 429:
            # 上限超過:指定された時間だけ待ってから送り直します
            time.sleep(int(res.headers.get("Retry-After", "1")))
            continue
        if res.status_code == 204:
            return res.status_code, None
        body = res.json()
        if not res.ok:
            raise RuntimeError(f"{body['error']['code']}: {body['error']['message']}")
        return res.status_code, body
    raise RuntimeError("rate_limited: 再試行の回数を超えました")


# 1) 画像
with open("cover.png", "rb") as f:
    _, cover = call("POST", "/uploads", files={"file": ("cover.png", f, "image/png")})

# 2) 記事(アップサート)
status, post = call("PUT", "/posts/external/prod-123", json={
    "lang": "ja",
    "slug": "product-123-review",
    "title": "商品123のレビュー",
    "thumbnail": cover["url"],
    "content": f"# 商品123\n\n![表紙]({cover['url']})",
    "categories": ["review"],
})
print("作成" if status == 201 else "更新", post["id"])

# 3) 下書きのときだけ公開
if post["status"] == "draft":
    _, published = call("POST", f"/posts/{post['id']}/publish")
    print(published["status"])  # "published"

 

自動化ツール・AIエージェント

  • n8n・Zapier・Make:HTTP Request ノードから上のパスをそのまま呼び出し、ヘッダーに Authorization: Bearer <キー> を入れます。同じ項目が何度も実行される可能性がある場合は、PUT /posts/external/{番号} を使ってください。同じ記事が二重に作られません。
  • AIエージェント:作成のみのキーを渡して下書きまでを作らせ、担当者がブログの画面で確認してから公開する運用をおすすめします。エージェントには、本文を Markdown で書き、コード例は ``` で囲むよう伝えてください。