LoginSignup
0
0

More than 3 years have passed since last update.

Qiita への記事更新を API 経由で行ってみる

Last updated at Posted at 2019-07-11

Hugo の記事の一部を Qiita へも投稿してみる。

ポイント

  • API v2 Document
  • 新規記事は POST、既存記事の更新は PATCH
  • title, body, tags ヘッダが無いと、400 Bad Request が返ってくる。
  • 「下書き」に関する項目は見つけられていない。 ヘッダ private は限定公開に関するものの様子。

サンプルコード

  • API Token は、環境変数 QIITA_TOKEN に保管してとってくる。

  • cryogen だとカスタムヘッダを追加できない・・


# -*- coding: utf-8 -*-
#
# Update an article via Qiita API
#
import sys
import os
import logging
import json
import requests

QIITA_URL = 'https://qiita.com/api/v2/items'

TAGS = ["qiita_id", "title", "tags"]

def parse(filepath, max_header_lines=10):
    u'''Parse original article (Cryogen format)'''
    title = None
    qiita_id = None
    tags = [{"name": "update_via_api", "version": []}]
    body = ''
    line_count = 0
    with open(filepath) as f:
        for line in f:
            line_count += 1
            if line.find(':qiita_id ') > 0:
                try:
                    qiita_id = line.strip().split()[1]
                except IndexError:
                    qiita_id = ''
            if line.find(':title ') > 0:
                title = line.strip().split(' ', 1)[1]
            if line.find(':tags ') > 0:
                keys = line.strip().split(' ', 1)[1]
                for k in json.loads(keys):
                    tags.append({"name": k, "version": []})
            if line.rstrip().endswith('}') or line_count > max_header_lines:
                break
        if qiita_id is None:
            return None
        for line in f:
            body += line
    return {
        'title': title,
        'qiita_id': qiita_id,
        'tags': tags,
        'body': body,
        'tweet': False,
        'private': False,
    }

def submit(item, token, url=QIITA_URL, article_id=None):
    u'''Submit to Qiita v2 API'''
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer {}'.format(token)
    }

    if article_id is None or article_id == '':
        res = requests.post(url, headers=headers, json=item)
    else:
        url = "{}/{}".format(url, article_id)
        res = requests.patch(url, headers=headers, json=item)
    if res.status_code >= 400:
        logging.error(res.json())
    res.raise_for_status()

    logging.info(json.dumps(res.json(), indent=2))

    return res

def execute(filepath, token):
    item = parse(filepath)
    if item is None:
        logging.warning("SKIP. No qiita_id tag found.")
        return
    logging.debug(json.dumps(item, indent=2))

    res = submit(item, token=token, article_id=item['qiita_id'])

if __name__ == "__main__":
    token = os.environ['QIITA_TOKEN']
    for arg in sys.argv[1:]:
        execute(arg, token)
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