Connecting to third party services is an everyday task for an app developer, not to mention connecting to social networks. Most of us have a long standing way of authenticating the user, acquiring data and performing tasks. A good way to do this on Android with Facebook, LinkedIn and Twitter is Spring’s Social framework, which is sadly missing Instagram. This is why Gyula Voros, one of my teammates at Ready took his time and wrote a library, which he made available as an open source project on GitHub. The library is pretty lightweight, the only dependency is Square’s Retrofit, hence the name retrogram. This post will show you how to use said library in an Android application.
The first step is including the library in your project. This can be done by referencing as a Maven dependency or downloading the source from GitHub. The current version is 1.0.2, the Maven dependency is the following:
<dependency> <groupId>com.getinch.retrogram</groupId> <artifactId>retrogram</artifactId> <version>1.0.2-SNAPSHOT</version> </dependency>
Usage is pretty simple. After you registered your app on the official API site with the proper permissions, you need to acquire an access token, which is responsible for authenticating the user. In Android this can be done by showing the official login site with a custom redirect url (this can be generated with the library’s Instagram.requestOAuthUrl() method), and after a successful attempt, the browser will redirect to said url with a param containing the token. Simply parse it using String matching and store it persistently (in Android, SharedPreferences is a good way to go). The following lines show a way to do this on Android with a DialogFragment:
As you can see, the code above is pretty simple, in a real-life scenario you should extend it with some sort of closing functionality (for example an x on one of the top corners) and progressdialogs for loading. And that’s it, the hard work is over, getting the user-specific objects is a piece of cake, basically you can get anything which is featured in the official APIdoc. Just create an Instagram instance with the previously acquired access token and call the proper object methods to perform the desired operations. A few examples:
Creating the Instagram istance:
final Instagram instagram = new Instagram("accessToken");
Querying a user with a specific ID:
final User user = instagram.getUsersEndpoint().getUser(userId);
Get the user’s feed:
final Feed feed = instagram.getUsersEndpoint().getFeed();
Like a specific image:
final boolean result = instagram.getLikesEndpoint().like(MediaId);
Get the followers of a given user (addressed by UserId)
final Followers followers = instagram.getRelationshipsEndpoint().getFollowers(UserId);
If you find any bugs or have some feature requests, feel free to contact us or fork the project on GitHub.