Tomas Romero
Tomas Romero

Reputation: 8698

How to retrieve Medium stories for a user from the API?

I'm trying to integrate Medium blogging into an app by showing some cards with posts images and links to the original Medium publication.

From Medium API docs I can see how to retrieve publications and create posts, but it doesn't mention retrieving posts. Is retrieving posts/stories for a user currently possible using the Medium's API?

Upvotes: 56

Views: 36448

Answers (12)

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11612

It is now 2024, and I have recently published an NPM package medium-sdk-ts -- my first ever library package!

It supports modern TypeScript and ESM syntax as well as older CommonJS as well.

The package supports fetching all published posts for a given user, and the best of all is that:

  • It handles pagination automatically.
  • It is completely FREE.
  • It is Open Sourced on GitHub.
  • No access token or authentication is required.

If curious, here is the Medium post I have written on it:

https://medium.com/@ritviknag/medium-api-with-javascript-in-2024-2e73440c7fa0

This other Medium post was the inspiration for my approach to Get the Published Posts of a User -- using GraphQL:

https://medium.com/@mike820324/web-crawler-getting-medium-post-a6e52fd36fd6

Usage

Install with npm or a package manager of choice:

npm i medium-sdk-ts

Then, to retrieve all public posts for a user:

import { MediumClient } from 'medium-sdk-ts';

// Access Token is optional, can also be set
// as environment variable `MEDIUM_ACCESS_TOKEN`
const medium = new MediumClient('YOUR_ACCESS_TOKEN');

// Get User's Published Posts (Title Only)
const posts = await medium.getPosts('@username');
console.log(`User Posts: ${JSON.stringify(posts, null, 2)}`);

The Problem with Existing Answers

Regarding RSS Feed:

https://medium.com/feed/@username

This works, but there is a limit and it only returns a user's 10 most recent posts.

https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/@USERNAME

Again, the above is a blatant copy-paste of https://medium.com/feed/@username approach. It just achieves the same end, and is limited to max of 10 posts.

https://api.medium.com/v1/users/{{userId}}/publications

The above answer totally miss the mark, unfortunately, It returns a user's publications which are different from their posts.

curl -i -H "Content-Type: application/json" -X POST -d '{"username":"nicolaerusan"}' https://clay.run/services/nicoslepicos/medium-get-users-posts-simple

Answers such as above were written a long time back. Most of them do not any longer work. For example the above link to clay.run - it leads to an API or page that doesn't exist anymore. Further, other solutions out there are not free and will require a subscription tier.

In short, the solution as I have outlined above works, and is completely Free and Open Sourced on GitHub.

Upvotes: 1

Hardik Pithva
Hardik Pithva

Reputation: 1745

Edit:

It is possible to make a request to the following URL and you will get the response. Unfortunately, the response is in RSS format which would require some parsing to JSON if needed.

https://medium.com/feed/@yourhandle

⚠️ The following approach is not applicable anymore as it is behind Cloudflare's DDoS protection.

If you planning to get it from the Client-side using JavaScript or jQuery or Angular, etc. then you need to build an API gateway or web service that serves your feed. In the case of PHP, RoR, or any server-side that should not be the case.

You can get it directly in JSON format as given beneath:

https://medium.com/@yourhandle/latest?format=json    

In my case, I made a simple web service in the express app and host it over Heroku. React App hits the API exposed over Heroku and gets the data.

const MEDIUM_URL = "https://medium.com/@yourhandle/latest?format=json";

router.get("/posts", (req, res, next) => {
  request.get(MEDIUM_URL, (err, apiRes, body) => {
    if (!err && apiRes.statusCode === 200) {
      let i = body.indexOf("{");
      const data = body.substr(i);
      res.send(data);
    } else {
      res.sendStatus(500).json(err);
    }
  });
});

Upvotes: 14

FrenchTechLead
FrenchTechLead

Reputation: 1146

I have created a custom REST API to retrieve the stats of a given post on Medium, all you need is to send a GET request to my custom API and you will retrieve the stats as a Json abject as follows: Request :

curl https://endpoint/api/stats?story_url=THE_URL_OF_THE_MEDIUM_STORY

Response:

{
   "claps": 78,
   "comments": 1
}

The API responds within a reasonable response time (< 2 sec), you can find more about it in the following Medium article.

Upvotes: 0

Alejandro Krumkamp
Alejandro Krumkamp

Reputation: 152

Nowadays this URL:

https://medium.com/@username/latest?format=json

sits behind Cloudflare's DDoS protection service so instead of consistently being served your feed in JSON format, you will usually receive instead an HTML which is suppose to render a website to complete a reCAPTCHA and leaving you with no data from an API request.

And the following:

https://medium.com/feed/@username

has a limit of the latest 10 posts.

I'd suggest this free Cloudflare Worker that I made for this purpose. It works as a facade so you don't have to worry about neither how the posts are obtained from source, reCAPTCHAs or pagination.

Full article about it.

Live example. To fetch the following items add the query param ?next= with the value of the JSON field next which the API provides.

Upvotes: 13

SHUBHAM SINGH
SHUBHAM SINGH

Reputation: 377

Use this url, this url will give json format of posts
Replace studytact with your feed name

https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/studytact

Upvotes: 4

Sabesan
Sabesan

Reputation: 702

To get your posts as JSON objects

you can replace your user name instead of @USERNAME.

https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/@USERNAME

Upvotes: 12

U.A
U.A

Reputation: 3373

const MdFetch = async (name) => {
  const res = await fetch(
    `https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/${name}`
  );
  return await res.json();
};

const data = await MdFetch('@chawki726');

Upvotes: 9

nicoslepicos
nicoslepicos

Reputation: 505

(Updating the JS Fiddle and the Clay function that explains it as we updated the function syntax to be cleaner)

I wrapped the Github package @mark-fasel was mentioning below into a Clay microservice that enables you to do exactly this:

Simplified Return Format: https://www.clay.run/services/nicoslepicos/medium-get-user-posts-new/code

I put together a little fiddle, since a user was asking how to use the endpoint in HTML to get the titles for their last 3 posts: https://jsfiddle.net/h405m3ma/3/

You can call the API as:

curl -i -H "Content-Type: application/json" -X POST -d '{"username":"nicolaerusan"}' https://clay.run/services/nicoslepicos/medium-get-users-posts-simple

You can also use it easily in your node code using the clay-client npm package and just write:

Clay.run('nicoslepicos/medium-get-user-posts-new', {"profile":"profileValue"})
.then((result) => {

  // Do what you want with returned result
  console.log(result);

})
.catch((error) => {

  console.log(error);

});

Hope that's helpful!

Upvotes: 1

Yash
Yash

Reputation: 114

Check this One you will get all info about your own post........

mediumController.getBlogs = (req, res) => {
    parser('https://medium.com/feed/@profileName', function (err, rss) {
        if (err) {
            console.log(err);
        }

        var stories = [];

        for (var i = rss.length - 1; i >= 0; i--) {

            var new_story = {};

            new_story.title = rss[i].title;
            new_story.description = rss[i].description;
            new_story.date = rss[i].date;
            new_story.link = rss[i].link;
            new_story.author = rss[i].author;
            new_story.comments = rss[i].comments;

            stories.push(new_story);
        }
        console.log('stories:');
        console.dir(stories);
        res.json(200, {
            Data: stories
        })
    });

}

Upvotes: 0

Mark Fasel
Mark Fasel

Reputation: 307

I have built a basic function using AWS Lambda and AWS API Gateway if anyone is interested. A detailed explanation is found on this blog post here and the repository for the the Lambda function built with Node.js is found here on Github. Hopefully someone here finds it useful.

Upvotes: 2

Antonio Brandao
Antonio Brandao

Reputation: 1452

The API is write-only and is not intended to retrieve posts (Medium staff told me)

You can simply use the RSS feed as such:

https://medium.com/feed/@your_profile

You can simply get the RSS feed via GET, then if you need it in JSON format just use a NPM module like rss-to-json and you're good to go.

Upvotes: 89

Casper Voogt
Casper Voogt

Reputation: 109

With that REST method you would do this: GET https://api.medium.com/v1/users/{{userId}}/publications and this would return the title, image, and the item's URL. Further details: https://github.com/Medium/medium-api-docs#32-publications .

You can also add "?format=json" to the end of any URL on Medium and get useful data back.

Upvotes: 5

Related Questions