Medium is one of the most popular blogging platforms, and having the ability to fetch and save an article as HTML can be incredibly useful. Whether you're archiving content, customizing its display, or embedding it into another application, fetching the HTML version of a Medium article opens up countless possibilities.
In this article, you'll learn how to retrieve and save a Medium article as HTML using the medium-api-js
package.
Before diving into the steps, make sure you have the following:
medium-api-js
package by running:npm install medium-api-js dotenv
This code uses the medium-api-js
library to fetch the HTML content of a specific Medium article.
Here is a step-by-step breakdown:
import Medium from 'medium-api-js';
import dotenv from 'dotenv';
dotenv.config();
Medium
: This is the main class from the medium-api-js
library, which provides various methods to interact with the Medium API.dotenv
: Enables the use of .env
files for storing sensitive data like the API key. The dotenv.config()
method loads the environment variables.const medium = new Medium(process.env.RAPIDAPI_KEY);
process.env.RAPIDAPI_KEY
: Fetches the API key from the .env
file. This ensures sensitive information is not hardcoded into the script.const articleId = '67fa62fc1971';
const fullPage = true; // Set to true if you want the full page
const styleFile = "dark.css"; // Set the css file name if you want to include the style file
articleId
: The unique identifier for the article you want to fetch. Replace this with the ID of the desired Medium article.fullPage
: A boolean flag indicating whether to fetch the full page or just the article body.styleFile
: Optional parameter to include a CSS file for styling the HTML content.medium.getArticleHTML(articleId, fullPage, styleFile)
.then(data => {
console.log('Article HTML:', data);
});
medium.getArticleHTML
: Fetches the HTML content for the specified article ID..then(data => {...})
: Handles the successful response from the API. The HTML content is logged to the console.Save the script as getArticleHTML.js
and run the following command in your terminal:
node getArticleHTML.js
If the request is successful, the script logs the HTML content of the specified article:
id
: Confirms the ID of the fetched article.html
: Contains the HTML content of the article, including any CSS specified.With medium-api-js
, fetching and saving Medium articles as HTML becomes a straightforward task. This script demonstrates how to retrieve an article's HTML content with customizable options for the full page and styling. Whether you’re building an archive or enhancing content presentation, this technique can be incredibly beneficial.
For questions or further assistance with the Medium API, feel free to reach out at nishu@mediumapi.com. Happy coding!