How To Build a Custom Command Line Tool to Interact with an API

A step-by-step guide to get you started


A custom command line tool is an ideal solution to quickly interact with an API. This is a useful tool to add to your toolbox to assist both yourself and/or clients with data they might need to upload or download from an API.


In this example, we use Python 3.6 with the fantastic Requests library to build our tool. Check out those links for more specific information on how to setup your local environment with these requirements.

Getting Started

from argparse import ArgumentParser
import csv
import json
from pprint import pprint
import requests

def read():
   product_list_url = 'http://localhost:8000/api/products/'
   response = requests.get(product_list_url)

   return response.json()

First, we import our libraries; then, we define a module that will send a get request to the API endpoint and return a response--thanks, Requests, for making this part pretty painless.

def preview(data):

Next, we define a method to display the data contained in the JSON response, returned from the API, to our console. We pass in the read() method.

def save(data):
   with open('product_data.csv', 'w') as f:
       field_names = ['id', 'name', 'product_id', 'description']
       writer = csv.DictWriter(f, fieldnames=field_names)

       for row in data.json():

Finally, we define a method to save our JSON response data to a CSV file which can be imported into a workbook spreadsheet using an application like Google Sheets.

Now, with our methods defined, we need a way to pass in arguments from the command line.

if __name__ == '__main__':
   parser = ArgumentParser(description='A command line tool for interacting with our API')
   parser.add_argument('-r', '--read', action='store_true', help='Sends a GET request to the product API.')
   parser.add_argument('-p', '--preview', action='store_true', help='Shows us a preview of the data.')

   args = parser.parse_args()

   if args.preview:
       print('Use the -h or --help flags for help')

Here, we instantiate an ArgumentParser object from the built in argparse library that comes with Python. We will call this object: parser.

We will use the add_argument method to define some arguments for parser to parse that we will pass in from the console. These arguments will give us some more control over our command line tool and make it more of an application and less of a script. We declare a variable called args and store the parse arguments in there.

Now, create a decision to evaluate conditions based on the arguments we’ve passed in. If no arguments are passed in, we supply some information on how to access the help option we created for our arguments above.

python -h

Type this command into the console--use python3 or python3.6 if you haven’t set up an alias to python--to see a list of commands and information on how to use them.

usage: [-h] [-r] [-p] [-s]

A command line tool for interacting with our API

optional arguments:
  -h, --help     show this help message and exit
  -r, --read     Sends a GET request to the product API.
  -p, --preview  Shows us a preview of the data.
  -s, --save     Saves the response to a CSV file.
python -rp

Type this command to see a preview of the data returned in the response from our API. Note: we use -rp. These are the shorthand arguments for --read and --preview.

[{'description': 'Some batteries.',
  'id': 3,
  'name': 'Off-Brand Batteries',
  'product_id': 'd2e800d3-2c66-4a69-921d-ff32037360e1'},
 {'description': 'Chargeable Batteries',
  'id': 4,
  'name': 'All Day Batteries',
  'product_id': 'aa8da0ed-9c1f-4407-b247-1cd7c4f88e49'},
 {'description': 'Non-Chargeable Batteries',
  'id': 5,
  'name': 'Not So All Day Batteries',
  'product_id': 'aa8da0ed-9c1f-4407-b247-1cd7c4f88e49'}]

And when we run it, we should get something like what we have above output to our console.

python -s

When we run this command, we save the response data to a CSV file named product_data.csv

3,Off-Brand Batteries,d2e800d3-2c66-4a69-921d-ff32037360e1,Some batteries.
4,All Day Batteries,aa8da0ed-9c1f-4407-b247-1cd7c4f88e49,Chargeable Batteries
5,Not So All Day Batteries,aa8da0ed-9c1f-4407-b247-1cd7c4f88e49,Non-Chargeable Batteries

This can be imported into a spreadsheet to share or present to our colleagues or clients, maybe both.


This covers the basics of downloading data from an API and saving that data to a CSV file. Next time, we will discuss uploading data from a CSV file to an API. We will add some more methods to our existing command line tool and demonstrate a basic use-case scenario.


Read our case studies

Lofty Labs is helping businesses solve problems with software solutions.