Skip to content

Instantly share code, notes, and snippets.

@postfalk
Last active July 25, 2017 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save postfalk/2830343c4cfea112fed10282d2fc6962 to your computer and use it in GitHub Desktop.
Save postfalk/2830343c4cfea112fed10282d2fc6962 to your computer and use it in GitHub Desktop.
Rivers Python Examples

Python examples for the Unimpaired Flows API

All Python example are written for Python 2.7.

  1. Install git from https://git-scm.com/ or copy code from below in your own project.
git clone https://gist.github.com/2830343c4cfea112fed10282d2fc6962.git pythonExamples
cd pythonExamples
  1. Install Python dependencies.
pip install -r requirements
  1. Run:
python basic_example.py

Run with jupyter

  1. Start notebook server, a web browser window will open.
jupyter notebook
  1. Open basic_example.ipynb

1. basic_example.py, basic_example.ipynb

Sends a simple request to /api/data/flat/ to demonstrate how to get data for a single stream segment.

2. pagination_example.ipynb

Demonstrates how to use pagination in code.

Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
"""Example creating Pandas data frame from API return.
Dependencies (install with pip): requests, pandas"""
import os
import json
import requests
from pandas.io.json import json_normalize
# API endpoint
FLOW_URL = 'https://rivers.codefornature.org/api/data/flat/'
# You could assign your token also directly,
# please make sure NOT to commit a valid token to a GitHub repository
STATUS_CODES = {
200: 'Success',
400: 'Malformed query',
401: 'Not authorized',
404: 'Not found',
504: 'Timed out. Request smaller batch of data.'}
def get_data(comid):
"""Function retrieving data for a single stream segment
Args:
comid(int): Comid for stream segment
Returns:
dict containing data.
"""
payload = {'where': json.dumps({'stream_segment': comid})}
res = requests.get(FLOW_URL, params=payload)
print 'Requested URL:', res.url
print 'Status:', res.status_code
if res.status_code == 200:
return json.loads(res.text)['results']
try:
print STATUS_CODES[res.status_code]
return
except KeyError:
print 'Something is wrong.'
if __name__ == '__main__':
res = get_data(4438300)
if res:
df = json_normalize(res)
print df
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
# requirements for running Python 2.7 examples
# install with
# pip install -r requirements.txt
jupyter==1.0.0
requests==2.13.0
pandas==0.19.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment