Skip to content

Instantly share code, notes, and snippets.

@weibeld
Created July 31, 2019 06:19
Show Gist options
  • Save weibeld/1e3770d093ca10266ecc3a565c9da38a to your computer and use it in GitHub Desktop.
Save weibeld/1e3770d093ca10266ecc3a565c9da38a to your computer and use it in GitHub Desktop.

Revisions

  1. weibeld created this gist Jul 31, 2019.
    71 changes: 71 additions & 0 deletions medium-article-with-canonical-link.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    #!/bin/bash

    set -e

    TITLE=$1
    CANONICAL_URL=$2

    if [[ "$#" -ne 2 ]]; then
    cat <<EOF
    USAGE
    $(basename $0) <TITLE> <CANONICAL_URL>
    ARGUMENTS
    TITLE Title of your article, used in Medium URL, can't be changed!
    CANONICAL_URL Canonical URL that this article should point to
    NOTES
    This script creates a draft article in your Medium account that includes a
    <link rel="canonical" ... /> tag pointing to your desired canonical URL. You
    can't set a canonical URL for an article through the Medium Web UI, that's
    why this script uses the Medium API:
    https://github.com/Medium/medium-api-docs
    After running this script, you will find the article as a draft in your
    Medium account where you can edit and publish it as usual. However, you
    can't change the canonical URL and the article title (the one used in the
    Medium URL of your article) anymore.
    To use the Medium API, you need an integration token, which you can request
    on the Medium help page:
    https://help.medium.com/hc/en-us/articles/213480228-Get-integration-token
    $(printf '\e[37;1m')IMPORTANT
    Before using this script, change the get-integration-token() function to
    print out your Medium integration token.$(printf '\e[0m')
    EOF
    exit
    fi

    # Abort if jq is not installed
    if ! which -s jq; then
    echo "You must install jq (e.g. 'brew install jq')"
    exit 1
    fi

    # Get your Medium integration token from wherever you have stored it
    get-integration-token() {
    # EDIT THIS PRINT YOUR INTEGRATION TOKEN
    aws secretsmanager get-secret-value --secret-id medium/integration-token --query SecretString --output text
    }

    # Get your Medium client ID from the Medium API (requires integration token)
    get-client-id() {
    curl -s -H "Authorization: Bearer $(get-integration-token)" \
    https://api.medium.com/v1/me | jq -r .data.id
    }

    # Create the article (https://github.com/Medium/medium-api-docs#creating-a-post)
    curl -s -X POST \
    -H "Authorization: Bearer $(get-integration-token)" \
    -H "Content-Type: application/json" \
    -d "{
    \"title\": \"$TITLE\",
    \"contentFormat\": \"html\",
    \"content\": \"<h1>Put your content here...</h1>\",
    \"canonicalUrl\": \"$CANONICAL_URL\",
    \"publishStatus\": \"draft\"
    }" \
    https://api.medium.com/v1/users/"$(get-client-id)"/posts | jq