[Golang] Get List of Instagram Stories


Interesting small program to get the JSON format data of the list of your following Instagram stories. The whole picture of getting the JSON comes from the post of Chrome IG Story [1]. Please read the post first. In this program only Go standard library is used, no third-party packages.

To access the Instagram API via local Go program, you need to login Instagram and get the following information from your browser:

  • ds_user_id
  • sessionid
  • csrftoken

Please see this SO answer to get above values on Chrome browser.

After you get the values, modify the following code to fill the values:

config.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package igstory

// Cookies information for accessing stories

// See the following Stack Overflow answer to get the values:
// https://stackoverflow.com/a/44773079
var config = map[string]string{
	"ds_user_id": "",
	"sessionid":  "",
	"csrftoken":  "",
	"User-Agent": "Instagram 10.3.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/420+",
}

After the values are set in the code, the following code can get JSON data of the list of your following Instagram stories:

allstories.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package igstory

// Get all stories of users that a user follows

import (
	"errors"
	"io/ioutil"
	"net/http"
	"strconv"
)

const UrlAllStories = `https://i.instagram.com/api/v1/feed/reels_tray/`

func GetAllStories(cfg map[string]string) (err error) {
	req, err := http.NewRequest("GET", UrlAllStories, nil)
	if err != nil {
		return
	}

	req.AddCookie(&http.Cookie{Name: "ds_user_id", Value: cfg["ds_user_id"]})
	req.AddCookie(&http.Cookie{Name: "sessionid", Value: cfg["sessionid"]})
	req.AddCookie(&http.Cookie{Name: "csrftoken", Value: cfg["csrftoken"]})

	req.Header.Set("User-Agent", cfg["User-Agent"])

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		err = errors.New("resp.StatusCode: " + strconv.Itoa(resp.StatusCode))
		return
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	println(string(b))

	return
}

Usage:

allstories_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package igstory

import (
	"testing"
)

func TestGetAllStories(t *testing.T) {
	err := GetAllStories(config)
	if err != nil {
		t.Error(err)
		return
	}
}

Tested on: Ubuntu Linux 17.10, Go 1.9.3.


References:

[1]Chrome IG Story — Bribing the Instagram Story API with cookies 🍪🍪🍪