#python スクリプトからMedium #API を叩いて新規ポストする例。公式APIリファレンスより。 @yumainaura
python スクリプトからMedium APIを叩いて新規ポストする例。
Guide
https://github.com/Medium/medium-api-docs#33-posts
Ref
- Medium #API で使えるトークンを設定する。サポートに問い合わせして有効化してもらった例。 · Issue #554 · YumaInaura/YumaInaura
- #python から Medium #API を叩いて自分のユーザー情報を取得する例 · Issue #556 · YumaInaura/YumaInaura
Run
AUTHOR_ID=xxxxxxxxxxx TOKEN=xxxxxxxxxxxx python example.py
Script
- 本運用ではcanonicalUrlは外す。canonical属性は重複排除のための HTMLの指定。
# -*- coding: utf-8 -*- # https://github.com/Medium/medium-api-docs#33-posts import requests import os url = 'https://api.medium.com/v1/users/{author_id}/posts'.format(author_id=os.environ['AUTHOR_ID']) token = os.environ['TOKEN'] headers = { 'Authorization': 'Bearer {}'.format(token), 'Content-Type': 'application/json', } json = { "title": "Liverpool FC", "contentFormat": "html", "content": "<h1>Liverpool FC</h1><p>You’ll never walk alone.</p>", "canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc", "tags": ["football", "sport", "Liverpool"], "publishStatus": "public" } res = requests.post(url, headers=headers, json=json) print(res.json())
Result
{u'data': {u'canonicalUrl': u'http://jamietalbot.com/posts/liverpool-fc', u'license': u'', u'title': u'Liverpool FC', u'url': u'https://medium.com/@YumaInaura/liverpool-fc-3c7cd8bad6ec', u'tags': [u'sports', u'football', u'liverpool'], u'authorId': u'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, u'publishedAt': 1549500000000, u'publishStatus': u'public', u'licenseUrl': u'https://medium.com/policy/9db0094a1e0f', u'id': u'3c7cd8bad6ec'}}
Script
トークンだけ指定すれば良いバージョン。
# -*- coding: utf-8 -*- import requests import os # Get Author Token url = 'https://api.medium.com/v1/me' token = os.environ['TOKEN'] headers = { 'Authorization': 'Bearer {}'.format(token), } res = requests.get(url, headers=headers) author_id = res.json()['data']['id'] print(res.json()) print "author id is {author_id}".format(author_id=author_id) # Post # https://github.com/Medium/medium-api-docs#33-posts url = 'https://api.medium.com/v1/users/{author_id}/posts'.format(author_id=author_id) token = os.environ['TOKEN'] headers = { 'Authorization': 'Bearer {}'.format(token), 'Content-Type': 'application/json', } json = { "title": "Liverpool FC", "contentFormat": "html", "content": "<h1>Liverpool FC</h1><p>You’ll never walk alone.</p>", "canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc", "tags": ["football", "sport", "Liverpool"], "publishStatus": "public" } res = requests.post(url, headers=headers, json=json) print(res.json())