Programmatically Publish Markdown as a Medium Story With Python
Use Medium’s publishing API to post content from your terminal (without losing much formatting)

Motivation: Slight Inconvenience

Problem Statement
When attempting to transfer an article draft from a local markdown file (usually exported from writing applications such as Bear or Notion) to Medium, the formatting does not paste well and it takes more than a good few minutes to re-adjust the formatting.
Thus, in true programmer’s fashion, the temptation begets an attempt to make the process slightly less painful.
The Solution
Make a command-line interaction (CLI) to read a local file and upload it to Medium as a new post, all while keeping the majority of the preset formatting (e.g. headers, links, code blocks) intact.
The Code
For brevity, not all codes will be included in the writing. The full code can be found here.
1. Get a Medium Integration Token
a. Account > Settings > Integration Tokens

b. Input token description and click “Get integration Token”

c. Copy the generated token

d. Add generated token to a python file as a constant variable
# file name: publish.pyTOKEN = 'insert_generated_medium_integration_token'
2. Set up a command-line interface
3. Preparing the file for publishing
The Medium post
API for publishing only accepts HTML and markdown content. Here’s the Python script to read the local markdown file:
Now let’s prepare the payload data by parsing the file contents.
4. Get author ID
To construct the URL to publish an article (later in point 5), an authorId
is required.
The authorId
can be obtained using the Users
endpoint with the integration token generated in point 1.
5. Publish file to Medium
With the authorId
and payload ready, use a POST request to publish the file content to Medium.
Result
Run the Python script from the command line to publish a local markdown to medium.
python publish.py draft_article.md --title "this is from the cli"


The same file added to Medium from the CLI keeps a lot of its formatting (e.g. headers, links, code blocks) from the original file and dramatically cuts down the time I took to complete this post.
Further Notes
- There was an attempt made to translate this into a web application, which was abandoned as the API currently does not support browser-based authentication
- The API does not upload local image references as images, a quick test finds that only URL-sourced images will translate into images being displayed in the post published by the CLI — a good exercise would be to have a way to perhaps use Medium’s image API to handle this scenario