Created
January 3, 2019 10:57
-
-
Save aebrahim/549ec653e046088312ef25320d184fe4 to your computer and use it in GitHub Desktop.
This script demonstrates an OpenMRS login followed by a REST API call.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# SPDX-License-Identifier: Apache-2.0 | |
import base64 | |
import urllib.request | |
import json | |
# Documentation of OpenMRS API here: | |
# https://wiki.openmrs.org/display/docs/REST+Web+Services+API+For+Clients | |
# This script demonstrates a login followed by an API call. | |
# Perform HTTP DELETE to get session cookie. | |
initial_delete = urllib.request.Request( | |
"https://my.site/openmrs/ws/rest/v1/session", | |
method="DELETE") | |
with urllib.request.urlopen(initial_delete) as response: | |
session_cookie = response.info()["Set-Cookie"] | |
# Perform HTTP Authentication with session cookie. | |
encoded = base64.b64encode(b"username:password") | |
send_pass = urllib.request.Request( | |
"https://my.site/openmrs/ws/rest/v1/session", | |
headers={"Cookie": session_cookie, "Authorization": b"Basic " + encoded}) | |
with urllib.request.urlopen(send_pass) as response: | |
parsed = json.loads(response.read().decode()) # decode needed in py < 3.6 | |
user_id = parsed["user"]["uuid"] | |
assert(parsed["authenticated"]) | |
# We will use these headers for our subsequent API requests. | |
headers = { | |
"Cookie": session_cookie, # Authentication | |
"Accept": "application/json", # Seems to be the default, but explicit! | |
} | |
# OpenMRS queries | |
# List all patients named John. | |
list_query = urllib.request.Request( | |
"https://my.site/openmrs/ws/rest/v1/person?q=John", | |
headers=headers) | |
with urllib.request.urlopen(list_query) as response: | |
parsed = json.loads(response.read().decode()) | |
patient_ids = {i["uuid"]: i["display"] for i in parsed["results"]} | |
# Get the record for each patient by UUID. | |
patients = {} | |
for pid in patient_ids: | |
read_query = urllib.request.Request( | |
"https://my.site/openmrs/ws/rest/v1/person/" + pid, | |
headers=headers) | |
with urllib.request.urlopen(read_query) as response: | |
patients[pid] = json.loads(response.read().decode()) | |
for pid in patient_ids: | |
print(patient_ids[pid]) | |
print(patients[pid]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment