How to Get Latest Medium Posts by Topic

(Using Medium API Python Package)

In this guide, you'll learn how to use the Medium API to fetch the latest posts on a specific topic. This involves using the medium-api Python library, which simplifies the process of interacting with Medium's API. Let's break down the steps to achieve this.

Prerequisite

Before you start, ensure you have the medium-api library installed. You can install it using pip:

pip install medium-api

Step-by-Step Guide

Here's a Python script that demonstrates how to get the latest posts for a given topic on Medium.

1. Import Libraries

The first step is to import the necessary libraries. We use the os module to access environment variables and the Medium class from the medium-api library to interact with the Medium API.

2. Get API Key from Environment

In this segment, we retrieve the API key from the environment variables. This key is necessary to authenticate our requests to the Medium API.

3. Create Medium Object

Here, we create an instance of the Medium class, passing the API key as an argument. This object will be used to make requests to the Medium API.

4. Fetch Latest Posts

In this code block, we use the latestposts method of the Medium object to fetch the latest posts on the topic of "blockchain". The fetch_articles method retrieves the articles associated with the topic. We print the number of article IDs returned to give an idea of how many posts were fetched.

5. Print Article Titles

Finally, we iterate over the articles returned and print their titles. This allows us to see the titles of the latest posts on the specified topic.

Summary

This script demonstrates how to fetch and display the latest Medium posts for a specific topic using the Medium API. By following these steps, you can easily adapt the code to retrieve posts on different topics or perform additional actions with the fetched data.

Output