Coder Social home page Coder Social logo

golang-instagram's Introduction

golang-instagram

A instagram API wrapper.

Features

Implemented:

  • All GET requests are implemented
  • Both authenticated and unauthenticated requests can be made
  • A nice iterator facility for paginated requests
  • No interface{} data types! (1 exception, see Location.Id note below)

Todo:

  • Authentication
  • POST / DELETE requests (you need special permissions for these so no way to test.)

Documentation

Documentation on godoc.org

Install

go get github.com/yanatan16/golang-instagram/instagram

Creation

import (
  "github.com/yanatan16/golang-instagram/instagram"
)

unauthenticatedApi := &instagram.Api{
  ClientId: "my-client-id",
}

authenticatedApi := &instagram.Api{
  AccessToken: "my-access-token",
}

- if enforceSigned false
anotherAuthenticatedApi := instagram.New("", "", "my-access-token", false)

- if enforceSigned true
anotherAuthenticatedApi := instagram.New("client_id", "client_secret", "my-access-token", false)

Usage

See the documentation, endpoint examples, and the iteration tests for a deeper dive than whats below.

import (
  "fmt"
  "github.com/yanatan16/golang-instagram/instagram"
  "net/url"
)

func DoSomeInstagramApiStuff(accessToken string) {
  api := New("", accessToken)

  if ok, err := api.VerifyCredentials(); !ok {
    panic(err)
  }

  var myId string

  // Get yourself!
  if resp, err := api.GetSelf(); err != nil {
    panic(err)
  } else {
    // A response has two fields: Meta which you shouldn't really care about
    // And whatever your getting, in this case, a User
    me := resp.User
    fmt.Printf("My userid is %s and I have %d followers\n", me.Id, me.Counts.FollowedBy)
  }

  params := url.Values{}
  params.Set("count", "1")
  if resp, err := api.GetUserRecentMedia("self" /* this works :) */, params); err != nil {
    panic(err)
  } else {
    if len(resp.Medias) == 0 { // [sic]
      panic("I should have some sort of media posted on instagram!")
    }
    media := resp.Medias[0]
    fmt.Println("My last media was a %s with %d comments and %d likes. (url: %s)\n", media.Type, media.Comments.Count, media.Like.Count, media.Link)
  }
}

There's many more endpoints and a fancy iteration wrapper. Check it out in the code and documentation!

Iteration

So pagination makes iterating through a list of users or media possible, but its not easy. So, because Go has nice iteration facilities (i.e. range), this package includes two useful methods for iterating over paginating: api.IterateMedias and api.IterateUsers. You can see the tests and the docs for more info.

// First go and make the original request, passing in any additional parameters you need
res, err := api.GetUserRecentMedia("some-user", params)
if err != nil {
  panic(err)
}

// If you plan to break early, create a done channel. Pass in nil if you plan to exhaust the pagination
done := make(chan bool)
defer close(done)

// Here we get back two channels. Don't worry about the error channel for now
medias, errs := api.IterateMedia(res, done)

for media := range medias {
  processMedia(media)

  if doneWithMedia(media) {
    // This is how we signal to the iterator to quit early
    done <- true
  }
}

// If we exited early due to an error, we can check here
if err, ok := <- errs; ok && err != nil {
  panic(err)
}

Tests

To run the tests, you'll need at least a ClientId (which you can get from here), and preferably an authenticated users' AccessToken, which you can get from making a request on the API Console

First, fill in config_test.go.example and save it as config_test.go. Then run go test

Notes

  • Certain methods require an access token so check the official documentation before using an unauthenticated Api. Also, there is a 5000 request per hour rate limit on any one ClientId or AccessToken, so it is advisable to use AccessTokens when available. This package will use it if it is given over a ClientId.
  • Location.Id is sometimes returned as an integer (in media i think) and sometimes a string. Because of this, we have to call it an interface{}. But there is a facility to force it to a string, as follows:
var loc Location
stringIdVersion := instagram.ParseLocationId(loc.Id)

If anyone can prove to me that they fixed this bug, just let me know and we can change it to a string (all other IDs are strings...)

  • created_time fields come back as strings. So theres a handy type StringUnixTimeStringUnixTime which has a nice method func (sut StringUnixTime) Time() (time.Time, error) that you can use to cast it to a golang time.
  • I apologize for using Medias [sic] everywhere, I needed a plural version that isn't spelled the same.

License

MIT-style. See LICENSE file.

golang-instagram's People

Contributors

fent avatar josephspurrier avatar penzur avatar xanderdwyl avatar yanatan16 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

golang-instagram's Issues

Drain Response.Body

Since you're using json.Decoder, I think it would be wise to drain response body for connection reuse. See relevant issue:
google/go-github#317
Discussion:
https://stackoverflow.com/questions/17948827/reusing-http-connections-in-golang
https://groups.google.com/forum/#!search/golang%2420json%2420decode%2420%2420io.Copy/golang-nuts/4Rr8BYVKrAI/ZrJJFTNleekJ
Solution to this would be something like this

defer func() {
    io.CopyN(ioutil.Discard, resp.Body, 512)
    resp.Body.Close()
}()

in here

defer resp.Body.Close()

If you want I can make a pull request.

Cheers.

OAuthAccessTokenException The access_token provided is invalid

Hello,

I am trying to use this package but even after generating long-lived API access token, It shows me error.

`api := instagram.New(cid,secret, token,true)

if ok, err := api.VerifyCredentials(); !ok {
	panic(err)
}`

error :

`panic: Error making api call: Code 400 OAuthAccessTokenException The access_token provided is invalid.`

What is the reason for this error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.