Skip to content

Instantly share code, notes, and snippets.

@psychemedia
Created September 6, 2017 16:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save psychemedia/155d81baf2f4320b4e3c9a0bb163c2ab to your computer and use it in GitHub Desktop.
Save psychemedia/155d81baf2f4320b4e3c9a0bb163c2ab to your computer and use it in GitHub Desktop.
Demo of a simple API defining Jupyter notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#!pip3 install jupyter_kernel_gateway"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import pandas as pd\n",
"import sqlite3\n",
"con = sqlite3.connect(\"onsgeocodes.sqlite\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"REQUEST = json.dumps({\n",
" 'path' : {},\n",
" 'args' : {}\n",
"})"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"jupyter kernelgateway --KernelGatewayApp.api='kernel_gateway.notebook_http' --KernelGatewayApp.seed_uri='./SimpleAPI.ipynb' "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# GET /ons/:code\n",
"request = json.loads(REQUEST)\n",
"code = request['path'].get('code')\n",
"\n",
"q='SELECT * FROM codelist WHERE \"GEOGCD\"=\"{code}\"'.format(code=code)\n",
"\n",
"\n",
"print('{\"codes\":%s}' % pd.read_sql_query(q, con).to_json(orient='records'))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# GET /ons/current/:name\n",
"request = json.loads(REQUEST)\n",
"name = request['path'].get('name')\n",
"\n",
"q='''\n",
"SELECT * FROM codelist JOIN metadata \n",
"WHERE \"GEOGNM\"=\"{name}\" AND codeAbbrv=sheet AND codelist.STATUS=\"live\"\n",
"'''.format(name=name)\n",
"\n",
"print('{\"codes\":%s}' % pd.read_sql_query(q, con).to_json(orient='records'))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment