Skip to content

Instantly share code, notes, and snippets.

@gwgundersen
Last active October 2, 2015 21:28
"""-------------------------------------------------------------------------------
- Use docstrings (https://www.python.org/dev/peps/pep-0008/#documentation-strings)
to describe each function at a high level. They are not always required, but I
think it's a good habit to write them.
- Internal functions should be prefixed with a single underscore
(https://www.python.org/dev/peps/pep-0008/#id41).
- `_url_encode` - I would not put implementation details in the a comment
describing the function. The user of a function should not care *how* the URL
is encoded.
- `type` is a reserved word in Python. Do not use reserve words for names. PEP8
suggests using a trailing underscore rather than abbreviations or spelling
corruption.
- Defining `url` - I like to use string formatting rather than concatenation. I
find it more readable. See http://stackoverflow.com/a/5082482.
- "# Get JSON from url." - Whenever you have a comment describing some code,
ask yourself if you can make your code so clear that it reads like the
comment. My preference is to reserve comments for things that are not
transparent to another developer, my future self included, e.g.: "I did this
weird hacky thing on purpose, because ABC bug! Do not just remove this hack
without fixing X, Y, and Z!"
- `if __name__ == '__main__':` - If you're writing a script that you'd like to
use from the command line, you should use this line of code. See:
https://stackoverflow.com/questions/419163/what-does-if-name-main-do.
----------------------------------------------------------------------------"""
import urllib.request
import urllib.parse
import json
def _read_url_as_json(url):
"""Reads and decodes response from URL, interpreting it as JSON."""
response = urllib.request.urlopen(url)
data = json.loads(response.read().decode('utf-8'))
return data
def _encode_url(url):
"""URL encodes the input string."""
return urllib.parse.quote(url)
def fetch_entity_by_name(type_, name):
"""Given an entity type and name, returns a JSON representation of the data.
"""
name = _encode_url(name)
type_ = _encode_url(type_)
url = 'http://amp.pharm.mssm.edu/Harmonizome/api/1.0/%s/%s' % (type_, name)
json_entity = _read_url_as_json(url)
return json_entity
def export_json_to_file(data, filename):
"""Writes JSON data to file."""
with open(filename, 'w') as out_file:
json.dump(data, out_file)
if __name__ == '__main__':
results = fetch_entity_by_name('dataset', 'PID pathways')
export_json_to_file(results, 'results.json')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment