DEV Community

loading...

Get pretty json API responses using a simple Python script

AK Adapa
Engineer by training with interests in biz/tech/world.
・1 min read

If you are searching for data or documents via websites, there is a good chance that the data is presented to you using REST API behind the scenes.

Sometimes, it could get tedious if you are using a website to get the same kind of information for different identifiers/keys. If this website has an API behind the scenes then you could straight way use that API. This could be achieved from your shell/Terminal using some simple tools.

This post is about using these 'tools' on a Mac OS:

assumed a website is using REST API GET requests such as this and response from this api is coming in JSON format...

https://api.website.com/lookup/byId?id=9876def

then, you could use a simple Python script as follows to get a pretty print of the JSON response right from the terminal.

import urllib2
import json

response = urllib2.urlopen('https://api.website.com/lookup/byId?id=9876def')

data = json.load(response)
formatted_data = json.dumps(data, indent=2)

print formatted_data
Enter fullscreen mode Exit fullscreen mode

Discussion (0)