How to authenticate Instagram in a command line application


Instagram uses OAuth to authenticate, meaning it can be kind of a drag to use its API if you don't want to build a web application. Building the simplest interface you can build to achieve your application's goals is one of the best ways to streamline your development process. And the simplest and cheapest interface is often the command line.

But because the OAuth handshake requires a web callback to operate, it can be cumbersome to build this authentication into a command line application. Below, I'll show you how to do it with only a little bit of annoyance.

Create an Instagram API Client

First, you'll want to go ask Instagram nicely for an API Client ID so you can get access to the Instagram API. Go to their developer portal and click 'Manage Clients' to add a new one.

When asked for URL's, feel free to use non-existent domains. I use for mine.

In the Security tab, be sure to uncheck "Disable implicit OAuth". This will allow you to connect to the API without requiring an explicit server-side post, meaning we can hijack the access token from the callback URL:

Uncheck 'Disable implicit OAuth'

Make a Firm Handshake

So what are you to do when you can't redirect your terminal window to Instagram so you can authorize your account? A little bit of copy-pasta. Here's what we're going to do:

  1. Generate an Instagram authorization URL and ask the user to paste it into their browser.
  2. The user will authenticate their Instagram account like usual. They'll be redirected to our dummy Redirect URI.
  3. We'll prompt the user for their newly-issued access token. Because we unchecked "Disable implicit OAuth" in our Instagram client configuration, the access token will be appended to the redirect URI. We'll ask them kindly to copy and paste it into the terminal.
  4. We'll be authenticated to Instagram in the terminal!
require 'instagram'

Instagram.configure do |config|
  config.client_id = "YOUR CLIENT ID"
  config.client_secret = "YOUR CLIENT SECRET"

# Generate an Instagram authorization URL
puts "Visit the Instagram OAuth URL below to get started:\n"
puts "" + ::Instagram.authorize_url(
  redirect_uri: ""
  response_type: 'token'

# Prompt the user for their newly-issued access token.
puts "Enter the access token at the end of the redirect URL.\nYou'll find it after the '#access_token=' in the URL."
access_token = gets.strip

# Create an Instagram client with the access token.
client = Instagram.client(access_token: access_token)

Now you should have an authenticated Instagram client. Use the Ruby Instagram API as usual:

for media_item in client.user_recent_media
  puts media_item.images.thumbnail.url

Store Your Access Token

Of course, requiring entering the access token each time we use our Instagram command line application is going to annoy our user. What if we could store the access token on the first authentication so we could use it for subsequent runs?

For this example, we'll store the access token in a file called .instagram-access-token. Depending on your application, you might want to use an existing YAML configuration file or another method.

require 'instagram'

# Configure the Instagram gem the same way we did above:
Instagram.configure do |config|
  config.client_id = settings.instagram_client_id
  config.client_secret = settings.instagram_client_secret

# If there's an access token saved to the file, then read it.
if File.exists?(".instagram-access-token")
  access_token =".instagram-access-token")
  # Otherwise, generate one
  puts "Visit the Instagram OAuth URL below to get started:\n"
  puts "" + ::Instagram.authorize_url(
    redirect_uri: ""
    response_type: 'token'

  # Prompt the user for their newly-issued access token.
  puts "Enter the access token at the end of the redirect URL.\nYou'll find it after the '#access_token=' in the URL."
  access_token = gets.strip

  # And save the token to the file for the next use:".instagram-access-token", 'w') do |file|

# Create an Instagram client with the access token.
client = Instagram.client(access_token: access_token)

As you can see above, we first check to see if there's an access token saved in our .instagram-access-token file. If there is, we skip the handshake process altogether. If not, we initiate the handshake.

Note that for the purposes of simplifying the example, I've left out some error handling for invalid access tokens. You'll want to verify that the access token stored is valid and go through the handshake process again if you cannot connect.


Building a command line application for Instagram is fairly easy, assuming you're able to build the authentication in a way that doesn't confuse your user. If you're just building a tool for personal use, this is a great way to create real value without incurring the burden of building a full-blown web application.

If you have questions or if something is unclear, please leave a comment below and I'll do my best to answer you.

Software is 10% Code

Building software is about programming, right? Day to day, we turn caffeine into code. We spend countless hours reading about new programming languages, techniques, and platforms. We engage in conferences, get into arguments about whose stack performs better, and scour Stack Overflow for the answers to our problems.

But none of that is programming. In fact, all of it—reading blogs, attending conferences, arguing, research—all of these activities are, at their core, interpersonal communication.

A good programmer knows the hottest programming language is English.

(Disclaimer: I speak English natively. Feel free to substitute your native tongue. I have no bias toward English and don't mind pressing '1'.)

Our stakeholders communicate their vision by telling us about it—in English. We capture their vision for development into well-crafted user stories—in English. We write our Stack Overflow questions in English, chat on Slack in English, and report bugs in English. So why do we look to techno-wizardry as solutions to problems whose root is likely poor team communication?

Bad Writing is a Meeting Factory

Being able to articulate a thought in writing means your team gets to take advantage of asynchronous communication. Whereas meetings are synchronous— requiring all parties to be present and engaged for the duration of the communication event—written communication is asynchronous, meaning the recipient can address your request or idea on their own time.

Understanding this distinction can save your team hours each day. If you're about to hold a meeting, ask whether it's because you don't feel confident writing an email to address the topic. Some topics are best discussed in person: "big picture" decisions and human resources concerns are a couple. But most technical decision-making is better left to the great text file in the sky.

Great Writing is Documentation

When ideas are birthed in writing, they're already documented. There's no need for a secretary in an email thread. No one need spend time writing meeting minutes or informing the team of decided action items. Your Slack channels are searchable.

This means that if we spend time to compose our thoughts concisely—if we re-read our message before sending and ensure we've articulated our thought as succinctly as we can muster—we have created a valuable artifact. We have contributed to our team's canon.

Resources for Better Writing

The Elements of Style

Strunk & White's classic prescriptive style guide The Elements of Style comprises "eight elementary rules of usage", ten "elementary principles of composition", "a few matters of form", a list of 49 "words and expressions commonly misused", and a list of 57 "words often misspelled." It's often cited as the standard for learning great writing style. I once kept a copy on my nightstand.

How to Win Friends and Influence People

Dale Carnegie's How to Win Friends and Influence People will help you adopt interpersonal skills to help win people to your way of thinking. Carnegie stresses that showing respect for other people's opinions and trying honestly to see things from the other person's point of view can dramatically change the way others perceive you. I think this is especially relevant to writing software, since there are often different but comparably adequate ways of approaching the same problem. Seeking to understand your team members' differing opinions can help you reach consensus. Adopting a sympathetic and concise writing style can help you do that.

Influence: The Psychology of Persuasion

This is the classic book on the science of persuasion. A word of warning: The tactics in this book can be (and are) used for some horribly manipulative things. But understanding the fundamentals of persuasion, how to coerce others, and how to defend against coercion, can be beneficial in your team diplomacy efforts.

One of the principles Cialdini covers, the contrast principle, can be used to dramatic effect when working with clients. The principle states that if we see two things in sequence that are different from one another, we will tend to see the second one as more different from the first than it actually is. This means that if we know Approach 1 is costly, but offer a more costly Approach 2 beside it, the client will likely accept Approach 1 by contrast. Consider the contrast principle when making proposals. It's likely you'll see an improvement in your team's buy-in to your ideas. Just don't take advantage of it.


When hiring technical talent, the first thing I look for is strong verbal communication skills. Being able to articulate ideas in writing is more valuable than technical skills because humans think in terms of and react to stories. Being able to tell stories that captivate your team and your customers creates consensus. When consensus is reached, the technicalities fall into place.

Writing is critical to your remote project because you don't get much face time. If you sign up for my free email course, I'll send you 12 patterns to make your remote team better. Sign up for free


Destiny USA

Photo is of Destiny USA, a shopping mall in Syracuse, New York formerly known as Carousel Center.

I grew up in several small towns scattered across western New York State. My childhood was one spent predominantly in the 1990s, a time of seeming economic prosperity. The shining beacon of consumer confidence in that period was the all-holy shopping mall. The veritable consumer church.

Raised in a typical, middle-class American family with a mother and a father, three children, a cat, two cars, a three-bedroom house, a pool, two incomes, and a healthy dose of suburban teenage angst, there were truly two escape hatches presented to the apprehensive adolescent: drugs & the mall. As a teenager, I never much fancied the idea of psychoactive substances and would not find my way into their clutches until later in life. At age sixteen, the mall offered emancipation from parents I didn't know I was lucky to have. A town square for the new recruits of the consumer class.

I have childhood memories of sitting on mall benches unboxing the latest computer games (Jedi Knight comes to mind), of meeting my family for dinner at the food court (I fucking loved Arby's), and my first awkward makeout sessions in the back of a matinee screening of The Crocodile Hunter: Collision Course. It is a unique condition of the consumer generations to feel nostalgic for time spent in shopping malls.

In college, I began experimenting with marijuana. Without going into too much detail about my experiences with the drug, one of the most notable effects was the gentle euphoric high I'd encounter when reminded of a favorable past event.

Fast forward to 2008. I'd been living in Portland for a few months and needed to shop for some clothes. I decided to shop the Lloyd Center mall near the city center. I took a few hits off my small pipe before entering. As soon as I walked in, the familiar mall smell hit my olfactory receptors and I was overcome with nostalgic euphoria and a sense of childish wistfulness. I was immediately drawn to stores which I'd frequented in my youth: Spencer Gifts, Hot Topic, EB Games. Somehow, despite my age, the experience gave me a sense of fullness. I'd walk into Barnes & Noble and immediately recount past experiences of shopping for books with friends in high school, of sipping my first Starbucks coffee in the cafe, of loitering because there was nothing else to do.

Soon, the prospect of rekindling that feeling became a mild addiction. I'd go mallsterbating at least once a month. I'd bring my laptop so I could sit in the food court and work on projects stoned out of my mind. I'd people-watch. I'd eat the shitty Chinese food and I'd loiter on benches. I'd seek out new malls -- mallsterbating in new cities was always my favorite. And, aside from the occasional coffee or lunch, I'd never spend a dime. Who shops in malls anymore, anyway?

I gave up my mallsterbating habit, but I'll always remember it as one of the most bizarre life experiences I've ever had. That I could trigger profound reminiscience of my youth with a couple tokes and a walk through a shopping mall is a testament to the virtues of enjoying simple pleasures.

Leaving my privately defined world

Leaving my privately defined world

My relationship with marijuana began like most teenagers. It was April 20th of my freshman year of college. My friends invited me to try taking rips from a three-foot blue-and-white bong filtered with ice during a break between classes. Being on the open-minded side of cautious, I asked myself what the harm was. And, as is allegedly typical among first-timers, I didn't get high. But my friends promised me I would if I had another go. So, a few days later I took a few hits from a small pipe. I remember the experience vividly. Music suddenly had a rejuvinated profundity, as if every deliberation of Cedric Bixler-Zavala's vocal melodies on the sophomore Mars Volta album Frances The Mute were just for me. When I closed my eyes, intense visual hallucinations spun on my eyelids, as if some part of my brain lay dormant, awaiting a rush of cannabanoids to unlock its gate.

As a rookie stoner, most basic tasks were unfathomable under the spell of the drug. I have memories of sitting in my car in a parking garage, watching the shapes of music take form on the canvas of my mind. I'd sit for a half hour, terrified at the prospect of interacting with other humans but content within the confines of my newfound cognitive adventure. I was hooked. But what did "hooked" mean, exactly? I certainly wasn't addicted. I didn't need marijuana in my life like a junkie needs heroin. I could function just fine without it. When I'd travel or visit family, I never craved cannabis. Marijuana just made everything better.

And, as so many users continue to believe, I thought it made me better, too. I felt more creative, more compassionate, and more grounded when under the influence of the drug. I had a sense of euphoria and oneness. It was as if I'd discovered a whole new mode of being.

Public perception of marijuana, especially in the United States, is becoming increasingly positive. 65 percent of adults between the ages of 18 and 32 support Marijuana legalization according to a Pew Research Center poll. In 2012, Washington and Colorado became the first states to legalize marijuana for recreational use. 20 states, along with the District of Columbia, have legalized marijuana for medical use. Pro-pot campaigns compare statistics surrounding the dangers of alcohol in defense of recreational cannabis legalization. A clever campaign video produced by a campaign organization for a marijuana referendum in British Columbia even goes as far as to compare alcohol to Microsoft and cannabis to Apple. With this kind of media acceptance, it's no wonder we're all toking.

After I finished college in 2007, I packed up and headed west. Here in Portland, I found a community of activists dedicated to the legalization movement, many of whom are medical marijuana cardholders. Despite still being illegal for recreational use in the state of Oregon, cannabis is as easy to obtain and less expensive per "dose" than alcohol. It also bears just about as much social stigma as alcohol, making it just another staple at house parties, on bar patios, and, as it would turn out, my living room.

In 2010, I purchased a marijuana vaporizer, an electronic device which heats plant matter to a temperature high enough to vaporize the active compounds in cannabis, but not high enough to combust the plant matter. This method of cannabis ingestion is arguably safer since fewer hazardous carcinogens are inhaled. Soon, I had a veritable marijuana appliance which became another "productivity tool" alongside my coffee cup. And the fact that my method of ingestion was physically harmless meant I saw no issue in more frequent use.

Calling cannabis a "productivity tool" may seem contradictory when I earlier mentioned I had trouble performing even the most basic tasks under the influence of the drug. As with all psychoactive substances, cannabis users experience diminishing returns as their bodies build tolerance to the drug and require more to achieve the same effect. In fact, many of the pleasant hallucinatory effects I mentioned earlier ceased within my first six months of use. Eventually, the cannabis high became less like a trip and more like a buzz.

Creatives profess achieving a state of flow, wherein they are fully immersed in their work with energized focus and enjoyment. Cannabis appeared to provide further immersion, to the point where I could sit at my computer for hours and produce without ever acknowledging the world beyond my screen. It also appeared to enhance my spatial reasoning abilities, a cornerstone of software engineering aptitude. I now know all of these apparent benefits to be erroneous.

In actuality, the alleged benefits of cannabis with respect to productivity and creativity are fabrications of the mind. In the same way cannabis conjures increased appreciation and admiration for art and music, so too it materializes false grandeur in the creative process. It's not that my ideas or execution were any better when I was stoned. They just appeared that way. At least, for the duration of the high.

Looking back, I realize most of the time I spent high I actually wasn't relaxed, euphoric, or productive. And it wasn't even enjoyable. I experienced, almost daily, symptoms of cannabis-induced acute psychosis. These included panic attacks, agoraphobia, aerophobia, hypochondria, persecutory delusions, mild sociopathic tendencies, and delusions of grandeur.

My first serious bout of panic occurred in the winter of 2010. I had just returned from an emergency trip to take care of my grandparents, both recently hospitalized. One night, I lit a joint in my bedroom, when suddenly I felt a horrific sense of doom come over me, as if I needed to escape from existence itself. My heart started racing and I felt intense pressure in my chest. Believing this was the start of a heart attack, I rushed myself to the emergency room. An EKG would later verify I had a healthy heart. In fact, at my doctor's request I completed a treadmill stress test and the technician told me I was the only patient she'd seen who made it all the way to the finish. My heart was fine. My brain certainly wasn't. My doctor suggested that cannabis was causing my anxiety and that I should discontinue use. But cannabis is harmless! Everyone knows that. I continued using.

Shortly after that episode, I made plans to visit a friend in Philadelphia. As I boarded the plane, an all-too-familiar sense of panic came over me. I clung to the armrests, palms sweating, breathing nervously for the entire duration of the flight. This continued for the next several years, despite knowing flying is the safest form of transportation per passenger-mile. Since stopping use, I haven't a shred of fear about my upcoming plane trip.

Similar to my fear of flying, I also suffered persecutory delusions wherein I believed, whether acutely or chronically, that something horrific was about to happen. In the case of boarding a plane, I believed we were certainly going to crash. I also, for a period of about two years, dwelled over the possibility of a catastropic earthquake striking the Cascades. I'd have persistent visions of the terror of fallen bridges and would panic if I were stopped in traffic underneath an overpass. The region is due for a catastrophic quake, but cannabis turned what should have been an exercise in humble preparedness into years of panic and dread.

But the most alarming side effect of my regular cannabis use was its subtle erosion of my empathy and capacity for interpersonal connection. People, mostly lovers, became mere instruments in a selfish, privately defined game with no winner. I found myself overly critical of every aspect of my lovers. One day I'd be head-over-heels in love. The next day, I'd have determined, by way of my own cannabis-fueled, paranoid means of analysis, that that person was insufficient. This cycle continued through one long-term relationship and countless casual dating encounters. I would become frustrated at the idea no one met my precise criteria, not recognizing the deadened and ill-natured disposition of my desires.

Most users are under the impression that because cannabis isn't physiologically addictive, they don't suffer withdrawal symptoms. Examining the reason for continuing use quickly debunks this myth. If the user believes pot makes everything better, then it should follow that their sober experiences would be, in contrast, worse. And that's the subtle trick that kept me toking for the better part of a decade. Cessation was surprisingly easy and I rarely experience cravings. When I do experience a craving, it's nothing like the infamous baby-on-the-ceiling scene from Trainspotting. Stopping pot was mostly an exercise in cognitive behavioral therapy, reprogramming my brain to understand that the alleged benefits of cannabis are mere illusions.

The dynamic of an abusive relationship is a reasonable analogy for my relationship with cannabis. Despite instinct telling me it's time to move on, pressures led me to persevere in the relationship. In spite of the misery, I became accustomed to the drug and took security in its presence.

Since stopping use, I've found myself more eager to help others and more in touch with the emotions of those around me. I operate in a space of emotional certainty, where I'm able to succinctly cast my desires and express my true feelings without lingering feelings of hesitation. And I want to engage in relationships not because of what I'll gain, but because of what I'll give.

Cannabis abuse is especially sinister because the consequences are so subtle they'll often go unrecognized. In the same way a functional alcoholic can continue to go through the motions of daily life, so too can the functional stoner exist and even excel in certain respects. Cannabis didn't take my home, my family, or my physical health. The dire consequence of chronic marijuana use is the steady corrosion of virtuous subjective experience.

I recognize the stigma surrounding drug addiction and understand I'm making a lot of admissions which could negatively effect my career and social life. However, I am choosing to take that risk with the hope that others might read my personal accounts and reevaluate their own recreational use of cannabis. If you're considering stopping, the /r/leaves community on Reddit is a great support resource. Literature on the subject is unfortunately sparse, but The Joy of Quitting Cannabis takes a positive, nothing-to-lose approach to the issue and was written by an ex-toker.

If you need me, I'll be busy getting high on life.