예시 코드

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\":\"ko\",\"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: 'ko',
  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": "ko",
    "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 에이전트: 작성 전용 키를 주고 초안까지만 만들게 한 뒤, 담당자가 블로그 화면에서 확인하고 발행하는 방식을 추천해요. 에이전트에게는 본문을 마크다운으로 쓰고 코드 예시는 ``` 로 감싸라고 알려 주세요.