[Golang] Get Instagram User ID
[Update]: The method in this post is no longer valid because Instagram does not allow access to ?__a=1 now. But we can still get user id from embedded data in HTML of user profile page. See my another post for more details.
Interesting small program to get Instagram user id, assume that user name is given. The method of getting id is found in the answer of Stack Overflow question [1]. No login or cookie required. We use only Go standard library to get id. No third-party packages are used.
The following is complete source code:
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 | package igstory // read user information, such as id, via username // see ``Instagram API -Get the userId - Stack Overflow`` // https://stackoverflow.com/a/44773079 import ( "encoding/json" "net/http" "strings" ) // no need to login or cookie to access this URL const UrlUserInfo = `https://www.instagram.com/{{USERNAME}}/?__a=1` type RawUserResp struct { User UserInfo } type UserInfo struct { Id string `json:"id"` Biography string `json:"biography"` } func GetUserInfo(username string) (userinfo *UserInfo, err error) { url := strings.Replace(UrlUserInfo, "{{USERNAME}}", username, 1) resp, err := http.Get(url) if err != nil { return } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) r := RawUserResp{} if err = dec.Decode(&r); err != nil { return } userinfo = &(r.User) return } |
If you want, you can take a look at the JSON response and get more information of the user.
Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package igstory import ( "testing" ) func TestGetUserInfo(t *testing.T) { iginfo, err := GetUserInfo("instagram") if err != nil { t.Error(err) return } t.Log(iginfo.Id) t.Log(iginfo.Biography) } |
Output:
=== RUN TestGetUserInfo
--- PASS: TestGetUserInfo (0.74s)
userinfo_test.go:13: 25025320
userinfo_test.go:14: Discovering — and telling — stories from around the world. Curated by Instagram’s community team.
PASS
Tested on: Ubuntu Linux 17.10, Go 1.9.3.
References:
[1] | Instagram API -Get the userId - Stack Overflow |