Get Medium Posts with Laravel

Arya Bawanta
May 18 · 3 min read

Medium is a big comminity blogging, which means you can create a community (called publication for next) and people can post in it. But sometimes we need some customized blog like wordpress, wix and other for whatever reasons you have. For me, I want to get posts from my medium publication and display it on my websites. I’m trying to use the Laravel PHP Framework.


Getting the Posts

Medium API

Medium have APIs with their services, but for posts, the APIs only provide to creating post, not retrieve them. Here is the Medium API Documentation link :

https://github.com/Medium/medium-api-docs

RSS Feed

So some ways to get the posts is by the RSS feed from this link :

https://medium.com/feed/{{userId or publicationId}}

But I want to store the posts instead getting the RSS feed when my websites opened, I want to get the actual content of the posts instead.

Actual Link

So, I need to know where my publication posts is located, of course it in my Medium Publication posts. The link looks like this :

https://medium.com/{{userId or publicationId}}

The link above will get the default User or Publication posts, for the latest posts or the trending posts, just add /trending or /latest behind above link. Now, that link will display the medium publication page, I want the JSON format. Luckily, it is a simple step, just add ‘format=json’ variable behind the url. The complete link will looks like this :

https://medium.com/{{userId or publicationId}}/trending?format=json

The result should be like this :

Cutted version of the posts

As you can see, the first line will includes , this is the Medium method to prevent the JSON hack. The JSON cant be decoded with those code, so the code need to be removed.


Getting Posts With Laravel

To get the posts, I used Guzzle, can be found here :

First of all, use the Guzzle class :

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use GuzzleHttp\TransferStats;

Get the Posts :

$client = new Client();
$result = $client->request('GET',
'https://medium.com/{{userId or publicationId}}/latest',
['query'=>['format'=>'json']])->getBody()->getContents();

Remove the JSON hack preventation (])}while(1);</x> ), I use explode and implode :

$posts = explode('])}while(1);</x>', $result);
$posts = implode('', $posts);

Lastly, decode the JSON :

$posts = json_decode($posts, true);

The posts is in $posts[‘payload’][‘posts’]. The result is :

JSON Decode Result

Now I can modify the data then add them the my customized website.


Closing

This is for a research Purpose. There’s many other things that maybe affecting this method. If you not sure enough, please dont use this method. For me, I’m still developt my site using some other method too. I hope this is helpul.


Gladly contact me for discussion,

I Gusti Ngurah Arya Bawanta

Arya Bawanta

Written by

A Full Stack System Developer