Repository: HHS/uts-rest-api Branch: master Commit: 51d78ef84abe Files: 36 Total size: 816.6 KB Directory structure: gitextract_ygghmsng/ ├── README.md └── samples/ ├── R/ │ ├── README.md │ └── UTS REST API - R starting kit - version 0.1.html ├── java/ │ ├── pom.xml │ ├── resources/ │ │ ├── findings.txt │ │ └── hpo-codes.txt │ └── src/ │ └── test/ │ └── java/ │ └── uts/ │ └── rest/ │ └── samples/ │ ├── classes/ │ │ ├── AtomLite.java │ │ ├── ConceptLite.java │ │ ├── SearchResult.java │ │ └── SourceAtomClusterLite.java │ ├── content/ │ │ ├── RetrieveAtomsTestCase.java │ │ ├── RetrieveCodeTestCase.java │ │ ├── RetrieveCuiTestCase.java │ │ └── WalkHierarchyTestCase.java │ ├── cookbook/ │ │ └── CodeCrosswalk.java │ ├── search/ │ │ ├── BatchTermToCuiOrCodeTestCase.java │ │ └── SearchTermsTestCase.java │ └── util/ │ └── RestTicketClient.java ├── perl/ │ ├── crosswalk.pl │ ├── lib/ │ │ └── Authentication/ │ │ └── TicketClient.pm │ ├── retrieve-atoms.pl │ ├── retrieve-cui-or-code.pl │ ├── search-terms.pl │ └── walk-hierarchy.pl └── python/ ├── Authentication.py ├── crosswalk.py ├── get-content-view-members.py ├── get-rxcui-ingredients.py ├── get-rxcui-status.py ├── get-rxcuis-by-tty.py ├── hpo-codes.txt ├── retrieve-cui-or-code.py ├── retrieve-usp-atoms-from-umls.py ├── retrieve-value-set-info.py ├── search-terms.py └── walk-hierarchy.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ # uts-rest-api (archived) This repository is no longer maintained. The scripts in this repository may no longer work as expected. For additional help with scripting against the UMLS API, see the following resources: [Python script examples](https://documentation.uts.nlm.nih.gov/rest/rest-api-cookbook/python-scripts.html) - A few sample python scripts that can help you to perform basic batch requests against the UMLS API. [Postman examples](https://documentation.uts.nlm.nih.gov/rest/rest-api-cookbook/postman.html) - API request examples that can be loaded in the Postman application. [UMLS Community](https://www.nlm.nih.gov/research/umls/implementation_resources/community/index.html) - A collection of user-contributed applications and scripts that extend the functionality of the UMLS. ================================================ FILE: samples/R/README.md ================================================ #R examples ================================================ FILE: samples/R/UTS REST API - R starting kit - version 0.1.html ================================================ UTS REST API - R starting kit - version 0.1
library('httr')
library('xml2')
library("knitr")
library("stringr")

User Authentication

MY_USERNAME <- "xxxxxxxxxxxxx"; 
MY_PASSWORD <- "xxxxxxxxxxxxx";

Getting a Ticket Granting Ticket (TGT) using UMLS credentials. The TGT is valid for 8 hours. You do not need a new TGT for each call to the REST API.

getTGT <- function(username, password) {
  AUTH_URI <- "https://utslogin.nlm.nih.gov/cas/v1/tickets"
  body <- list(username = username, password = password)
  TGT_RESPONSE <- POST(AUTH_URI, body = body, encode = "form")
  warn_for_status(TGT_RESPONSE)
  TGT_uri       <- headers(TGT_RESPONSE)$location
  TGT_timestamp <- Sys.time()
  return(list(TGT_uri,TGT_timestamp) )
}

tgt <- getTGT(MY_USERNAME,MY_PASSWORD)

paste("TGT=", str_split(tgt, "/")[[1]][7])
## [1] "TGT= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"

Getting a Service Ticket (ST), good for one call. A ST will expire after 5 minutes if not used.

getST <-function(TGT,VERBOSE) {
  timeout(15)
  AUTH_URI <- paste(tgt[[1]])
  ST_RESPONSE <- POST(AUTH_URI, 
                      body = list(service = "http://umlsks.nlm.nih.gov"), 
                      encode = "form")
  
  warn_for_status(ST_RESPONSE)
  ST <- content(ST_RESPONSE)
  
  if(VERBOSE){
    print(paste("getST: ", http_status(ST_RESPONSE)$message, sep = ""))
    print(paste("     st= ", ST, sep = ""))
    print(paste("    tgt= ", str_split(tgt, "/")[[1]][7], sep = ""))
  }

  # no sleeping time neccessary of run at LHC
  # random sleep of 5-10ms for each ST
  # sleep_time <- round(runif(1, 0.005, 0.010), digits = 3) 
  # Sys.sleep(sleep_time)
  
  return(ST)
}
paste("st=[", getST(tgt, TRUE),"]",sep="")
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442113-nPt1AMRHxsObj3n0kLc3-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "st=[ST-1442113-nPt1AMRHxsObj3n0kLc3-cas]"

Searching the UMLS

getCUI <-function(STRING,SEARCH_TYP,VERSION,VERBOSE){
  
  if(! SEARCH_TYP %in% c("exact","words","leftTruncation","rightTruncation","approximate","normalizedString")){
    warning("Invalid search type")
    break
  }

  if(VERBOSE){
      print(paste("START getCUI for [", STRING, "][",SEARCH_TYP,"]", sep = ""))
  }
  
  timeout(5)
  SEARCH_URI <- paste("https://uts-ws.nlm.nih.gov/rest/search",VERSION, sep = "/")

  concepts       <- list()
  page           <- 0
  attempt        <- 0
  MAX_attempt    <- 6        # maximum number of tries if a http error occurs [6 is good]
  SNOOZE_time    <- 10       # time (seconds) of the pause when error occurs [10 is good]
  Res            <- NULL
  sleep_time     <- 0        # no sleeping time neccessary of run at LHC
  
  repeat{
    
    page <- (page+1)
    concepts_cnt <- length(concepts)
    
    QUERY = list(string = STRING, 
                 ticket = getST(tgt, VERBOSE),
                 searchType=SEARCH_TYP,
                 pageNumber=page)
    
    response <- GET(url=SEARCH_URI, query=QUERY)
    
    # no sleeping time neccessary of run at LHC
    # sleep_time <- round(runif(1, 0.015, 0.025), digits = 3) # random sleep of 10-25ms
    # Sys.sleep(sleep_time)
    
    if(VERBOSE){
      print(paste("getCUI: random sleep (sec)= ", sleep_time, sep = ""))
    }
    
    
    if(http_error(response)){
      page <- 0

      if(attempt<MAX_attempt){
        attempt <- (attempt + 1)
        sleep_time <- SNOOZE_time*attempt*runif(1,0.5,1)
        message_for_status(response, paste("mapping term [", STRING, "]", 
                                           "[Attempt #", attempt, "]", 
                                           sep = ""))
        print(paste("[Now taking a ", sleep_time, " sec break]", sep = ""))

        Sys.sleep(sleep_time)
        next
      }
      stop("Too many failures, unable tor perform mapping.")
    }
    else
    {
      Res <- content(response)
      for(i in 1:length(Res$result$results)){
        concepts[[concepts_cnt+i]] <- c(Res$result$results[[i]]$ui,
                                        Res$result$results[[i]]$name,
                                        Res$result$results[[i]]$rootSource,
                                        Res$result$results[[i]]$uri)
      }
    }
    if(Res$result$results[[1]]$ui == "NONE"){
      break
    }
  }
  
  if(length(concepts) > 1){
    if(VERBOSE){
      print(paste("END getCUI for [", STRING, "][",(length(concepts)-1)," CUI found]", sep = ""))
    }
    concepts <- concepts[1:(length(concepts)-1)]
  }
  else
  {
    if(VERBOSE){
      print(paste("END getCUI for [", STRING, "][0 CUI found]", sep = ""))
    }
    concepts[[1]] <- c("NO_CONCEPT_MAPPED_TO","","","")
  }
  
  return(concepts) 
}
#
getCUI("fracture of carpal bone","exact","2015AB", TRUE)
## [1] "START getCUI for [fracture of carpal bone][exact]"
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442114-zqywcCRkMnD2YSG93Ld5-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "getCUI: random sleep (sec)= 0"
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442115-S0QKlt9SfE5eTnQoSeHZ-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "getCUI: random sleep (sec)= 0"
## [1] "END getCUI for [fracture of carpal bone][1 CUI found]"
## [[1]]
## [1] "C0016644"                                                   
## [2] "Fracture of carpal bone"                                    
## [3] "MTH"                                                        
## [4] "https://uts-ws.nlm.nih.gov/rest/content/2015AB/CUI/C0016644"
getCUI("fracture of carpal bone","exact","2015AB", FALSE)
## [[1]]
## [1] "C0016644"                                                   
## [2] "Fracture of carpal bone"                                    
## [3] "MTH"                                                        
## [4] "https://uts-ws.nlm.nih.gov/rest/content/2015AB/CUI/C0016644"
#
getCUI("fracture of the carpal bone","exact","2015AB", FALSE)
## [[1]]
## [1] "NO_CONCEPT_MAPPED_TO" ""                     ""                    
## [4] ""
getCUI("fracture of the carpal bone","normalizedString","2015AB", FALSE)
## [[1]]
## [1] "C0016644"                                                   
## [2] "Fracture of carpal bone"                                    
## [3] "MTH"                                                        
## [4] "https://uts-ws.nlm.nih.gov/rest/content/2015AB/CUI/C0016644"

Mapping to UMLS (EM then NSI)

This was tested on 15,162 terms, done 44.12 mins (over NIH Guest wifi)

map_to_umls <-function(STRING,VERSION, VERBOSE){
  
  if(VERBOSE){
    print(paste("###==[MAP TO UMLS]==>"))
    print(paste("START map_to_umls for [", STRING, "]", sep = ""))
    print(paste("--> LOOKING FOR EM FOR  [", STRING, "]", sep = ""))
  }
  
  MAPPING_list <- list()
  MAPPING_typ  <- "NO_CONCEPT_MAPPED_TO"
  MAPPING_count <- 0
  
  
  EM_list      <- getCUI(STRING,"exact",VERSION, VERBOSE)
  
  if(EM_list[[1]][1] == MAPPING_typ){
    
    if(VERBOSE){
      print(paste("----> LOOKING FOR NSI FOR [", STRING, "]", sep = ""))
    }
    
    NSI_list <- getCUI(STRING,"normalizedString",VERSION, VERBOSE)
    
    if(NSI_list[[1]][1] != MAPPING_typ){
      MAPPING_list <- NSI_list
      MAPPING_typ  <- "NSI"
      MAPPING_count <- length(MAPPING_list)
    }
    else
    {
      if(VERBOSE){
        print(paste("--X-X-> NO EM NOR NSI FOR [", STRING, "]", sep = ""))
      }
      MAPPING_list[[1]] <- c("","","","")
    }
    
  }
  else
  {
    MAPPING_list <- EM_list
    MAPPING_typ  <- "EM"
    MAPPING_count <- length(MAPPING_list)
  }
  
  i<-0
  while(i<length(MAPPING_list)){
    i<-i+1
    MAPPING_list[[i]][5] <- paste(STRING, MAPPING_typ, MAPPING_count, 
                                  MAPPING_list[[i]][1], MAPPING_list[[i]][2], 
                                  MAPPING_list[[i]][3], sep = "|")
  }
  
  if(VERBOSE){
    print(paste("END map_to_umls for [", STRING, "]", sep = ""))
  }
  
  return(MAPPING_list)
}

some functions to manage various outputs of mapping to UMLS (split/noSplit)

# to retrive a list with 1 mapping per line
getMappingSplitList <- function(MAPPINGS){
  splitList <- list()
  for(i in 1:length(MAPPINGS)){
    splitList[i] <- MAPPINGS[[i]][5]
  }
  return(splitList)
}

# to retrive a list with all mappings on 1 line
getMappingNoSplitList <- function(MAPPINGS){
  
  STRING        <- strsplit(MAPPINGS[[1]][5], "|",fixed = TRUE)[[1]][1]
  MAPPING_typ   <- strsplit(MAPPINGS[[1]][5], "|",fixed = TRUE)[[1]][2]
  MAPPING_count <- strsplit(MAPPINGS[[1]][5], "|",fixed = TRUE)[[1]][3]
  
  noSplitList <- paste(STRING,MAPPING_typ,MAPPING_count, sep="|")
  
  if(MAPPING_count == 0){
    return(noSplitList)
  }
  else{
    cuis  <- character()
    names <- character()
    for(i in 1:length(MAPPINGS)){
      cuis <-  paste(cuis,  list(MAPPINGS[[i]][1]), sep = "|")
      names <- paste(names, list(MAPPINGS[[i]][2]), sep = "|")
    }
    noSplitList <- paste(noSplitList, cuis, names, sep = "")
    return(noSplitList)
  }
}
map_to_umls("fetus","2015AB", TRUE)
## [1] "###==[MAP TO UMLS]==>"
## [1] "START map_to_umls for [fetus]"
## [1] "--> LOOKING FOR EM FOR  [fetus]"
## [1] "START getCUI for [fetus][exact]"
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442121-qop9Mistx63ZJPpf9W5b-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "getCUI: random sleep (sec)= 0"
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442122-1Y4s6jmSjgPPy44GVBds-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "getCUI: random sleep (sec)= 0"
## [1] "END getCUI for [fetus][3 CUI found]"
## [1] "END map_to_umls for [fetus]"
## [[1]]
## [1] "C0015965"                                                   
## [2] "Fetus"                                                      
## [3] "MTH"                                                        
## [4] "https://uts-ws.nlm.nih.gov/rest/content/2015AB/CUI/C0015965"
## [5] "fetus|EM|3|C0015965|Fetus|MTH"                              
## 
## [[2]]
## [1] "C0242291"                                                   
## [2] "Fetal Tissue"                                               
## [3] "MTH"                                                        
## [4] "https://uts-ws.nlm.nih.gov/rest/content/2015AB/CUI/C0242291"
## [5] "fetus|EM|3|C0242291|Fetal Tissue|MTH"                       
## 
## [[3]]
## [1] "C1305737"                                                   
## [2] "Entire fetus"                                               
## [3] "MTH"                                                        
## [4] "https://uts-ws.nlm.nih.gov/rest/content/2015AB/CUI/C1305737"
## [5] "fetus|EM|3|C1305737|Entire fetus|MTH"
map_to_umls("fetal medicine","2015AB", TRUE)
## [1] "###==[MAP TO UMLS]==>"
## [1] "START map_to_umls for [fetal medicine]"
## [1] "--> LOOKING FOR EM FOR  [fetal medicine]"
## [1] "START getCUI for [fetal medicine][exact]"
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442123-B5pOLyeaVLZ4RFYE9lD1-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "getCUI: random sleep (sec)= 0"
## [1] "END getCUI for [fetal medicine][0 CUI found]"
## [1] "----> LOOKING FOR NSI FOR [fetal medicine]"
## [1] "START getCUI for [fetal medicine][normalizedString]"
## [1] "getST: Success: (200) OK"
## [1] "     st= ST-1442124-TD1JmJKCwzTsKHwj1Poj-cas"
## [1] "    tgt= TGT-200264-Il9XrohIp6DKkRcEzYjwLtIbdzO3V6ce31VcF7bUe7d4q2uqNb-cas"
## [1] "getCUI: random sleep (sec)= 0"
## [1] "END getCUI for [fetal medicine][0 CUI found]"
## [1] "--X-X-> NO EM NOR NSI FOR [fetal medicine]"
## [1] "END map_to_umls for [fetal medicine]"
## [[1]]
## [1] ""                                        
## [2] ""                                        
## [3] ""                                        
## [4] ""                                        
## [5] "fetal medicine|NO_CONCEPT_MAPPED_TO|0|||"
s <- "fetus"
mappings <- map_to_umls(s,"2015AB", FALSE)
getMappingSplitList(mappings)
## [[1]]
## [1] "fetus|EM|3|C0015965|Fetus|MTH"
## 
## [[2]]
## [1] "fetus|EM|3|C0242291|Fetal Tissue|MTH"
## 
## [[3]]
## [1] "fetus|EM|3|C1305737|Entire fetus|MTH"
getMappingNoSplitList(mappings)
## [1] "fetus|EM|3|C0015965|C0242291|C1305737|Fetus|Fetal Tissue|Entire fetus"
sessionInfo()
## R version 3.2.3 (2015-12-10)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: OS X 10.11.3 (El Capitan)
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] stringr_1.0.0 knitr_1.12.3  xml2_0.1.2    httr_1.1.0   
## 
## loaded via a namespace (and not attached):
##  [1] R6_2.1.1        magrittr_1.5    formatR_1.2.1   tools_3.2.3    
##  [5] htmltools_0.2.6 curl_0.9.6      yaml_2.1.13     Rcpp_0.12.1    
##  [9] stringi_0.5-5   rmarkdown_0.9.5 jsonlite_0.9.19 digest_0.6.8   
## [13] evaluate_0.8
================================================ FILE: samples/java/pom.xml ================================================ 4.0.0 gov.nih.nlm.uts.api.rest.samples uts-rest-api-samples 0.0.1-SNAPSHOT UTS REST API Samples central Maven Central Repository https://repo1.maven.org/maven2 commons-lang commons-lang 2.6 junit junit 4.12 com.jayway.restassured rest-assured 2.4.0 com.jayway.jsonpath json-path 2.0.0 com.jayway.restassured xml-path 2.4.0 com.fasterxml.jackson.core jackson-core 2.9.7 com.fasterxml.jackson.core jackson-annotations 2.9.7 com.fasterxml.jackson.core jackson-databind 2.10.0.pr1 com.codesnippets4all quick-json 1.0.4 log4j log4j 1.2.17 ================================================ FILE: samples/java/resources/findings.txt ================================================ diabetic foot kidney stones plantar fasciitis subarachnoid hemorrhage metatarsal fracture bloom syndrome Glycogen storage disease Leigh Syndrome idiopathic neuropathy nephritis systemic lupus erythematosus neonatal hypoglycemia ================================================ FILE: samples/java/resources/hpo-codes.txt ================================================ HP:0001735 HP:0001947 HP:0100631 HP:0001022 HP:0001596 HP:0000646 HP:0009916 HP:0100845 HP:0001102 HP:0000739 HP:0000787 HP:0011484 HP:0001871 HP:0030346 ================================================ FILE: samples/java/src/test/java/uts/rest/samples/classes/AtomLite.java ================================================ package uts.rest.samples.classes; import com.fasterxml.jackson.annotation.*; //ignorable properties are of customizable - this is just an example @JsonIgnoreProperties({"classType","attributes","definitions","relations","contentViewMemberships"}) public class AtomLite { private String ui; private String name; private String termType; private String language; private boolean suppressible; private boolean obsolete; private String rootSource; private String concept; private String code; private String sourceConcept; private String sourceDescriptor; private String parents; private String children; private String ancestors; private String descendants; public String getUi() { return this.ui; } public String getName() { return this.name; } public String getTermType() { return this.termType; } public String getLanguage() { return this.language; } public String getConcept() { return this.concept; } public String getSourceConcept() { return this.sourceConcept; } public String getSourceDescriptor() { return this.sourceDescriptor; } public String getCode() { return this.code; } public boolean getObsolete() { return this.obsolete; } public boolean getSupressible() { return this.suppressible; } public String getRootSource() { return this.rootSource; } public String getParents() { return this.parents; } public String getChildren() { return this.children; } public String getAncestors() { return this.ancestors; } public String getDescendants() { return this.descendants; } private void setUi(String ui) { this.ui = ui; } private void setTermType(String termType){ this.termType = termType; } private void setName(String name) { this.name = name; } private void setLanguage (String language) { this.language = language; } private void setObsolete (boolean obsolete) { this.obsolete = obsolete; } private void setRootSource(String rootSource) { this.rootSource = rootSource; } private void setSuppressible (boolean suppressible) { this.suppressible = suppressible; } private void setParents (String parents) { this.parents = parents; } private void setChildren (String children) { this.children = children; } public void setAncestors (String ancestors) { this.ancestors = ancestors; } public void setDescendants (String descendants) { this.descendants = descendants; } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/classes/ConceptLite.java ================================================ package uts.rest.samples.classes; import java.util.HashMap; import java.util.List; import com.fasterxml.jackson.annotation.*; //of course these are customizable @JsonIgnoreProperties({"classType","dateAdded","majorRevisionDate","status","attributeCount","cvMemberCount","suppressible","relationCount"}) public class ConceptLite { private String ui; private String name; private List> semanticTypes; private int atomCount; private String atoms; private String relations; private String definitions; private String defaultPreferredAtom; public String getUi() { return this.ui; } public String getName() { return this.name; } public List> getSemanticTypes() { return this.semanticTypes; } public String getAtoms() { return this.atoms; } public int getAtomCount() { return this.atomCount; } public String getDefinitions() { return this.definitions; } public String getRelations() { return this.relations; } public String getDefaultPreferredAtom() { return this.defaultPreferredAtom; } private void setAtoms(String atoms) { this.atoms = atoms; } private void setUi(String ui) { this.ui = ui; } private void setName(String name){ this.name=name; } public void setSemanticTypes(List> stys) { this.semanticTypes = stys; } private void setDefinitions (String definitions) { this.definitions = definitions; } private void setRelations (String relations) { this.relations = relations; } private void setDefaultPreferredAtom(String defaultPreferredAtom) { this.defaultPreferredAtom = defaultPreferredAtom; } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/classes/SearchResult.java ================================================ package uts.rest.samples.classes; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; public class SearchResult { private String ui; private String name; private String uri; private String rootSource; //getters public String getUi() { return this.ui; } public String getName() { return this.name; } public String getUri() { return this.uri; } public String getRootSource() { return this.rootSource; } //setters private void setUi(String ui) { this.ui = ui; } private void setName(String name) { this.name = name; } private void setUri(String uri) { this.uri = uri; } private void setRootSource(String rootSource) { this.rootSource = rootSource; } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/classes/SourceAtomClusterLite.java ================================================ package uts.rest.samples.classes; import java.util.HashMap; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties({"classType"}) public class SourceAtomClusterLite { private String ui; private String name; private boolean obsolete; private boolean suppressible; private String rootSource; private int cVMemberCount; private int atomCount; private String concepts; private String atoms; private String parents; private String children; private String descendants; private String ancestors; private String relations; private String definitions; private String attributes; private String defaultPreferredAtom; private List> subsetMemberships; private List> contentViewMemberships; public String getUi() { return this.ui; } public String getName() { return this.name; } public boolean getObsolete() { return this.obsolete; } public boolean getSuppressible() { return this.suppressible; } public String getAtoms() { return this.atoms; } public String getConcepts() { return this.concepts; } public String getRootSource() { return this.rootSource; } public int getAtomCount() { return this.atomCount; } public int getCVMemberCount() { return this.cVMemberCount; } public String getParents() { return this.parents; } public String getChildren() { return this.children; } public String getAncestors() { return this.ancestors; } public String getDescendants() { return this.descendants; } public String getDefinitions() { return this.definitions; } public String getRelations() { return this.relations; } public String getAttributes() { return this.attributes; } public String getDefaultPreferredAtom() { return this.defaultPreferredAtom; } private List> getSubsetMemberships() { return this.subsetMemberships; } private List> getContentViewMemberships() { return this.contentViewMemberships; } private void setAtoms(String atoms) { this.atoms = atoms; } private void setAtomCount(int atomCount) { this.atomCount = atomCount; } private void setcVMemberCount(int cVMemberCount) { this.cVMemberCount = cVMemberCount; } private void setUi(String ui) { this.ui = ui; } private void setConcepts(String concepts) { this.concepts = concepts; } private void setName(String name){ this.name=name; } private void setRootSource(String rootSource) { this.rootSource = rootSource; } private void setObsolete(boolean obsolete) { this.obsolete = obsolete; } private void setSuppressible(boolean suppressible) { this.suppressible = suppressible; } private void setDefinitions (String definitions) { this.definitions = definitions; } private void setRelations (String relations) { this.relations = relations; } private void setChildren(String children) { this.children = children; } private void setParents(String parents) { this.parents = parents; } private void setAncestors(String ancestors) { this.ancestors = ancestors; } private void setAttributes(String attributes) { this.attributes = attributes; } private void setDefaultPreferredAtom(String defaultPreferredAtom) { this.defaultPreferredAtom = defaultPreferredAtom; } private void setContentViewMemberships(List> contentViewMemberships) { this.contentViewMemberships = contentViewMemberships; } private void setSubsetMemberships(List> subsetMemberships) { this.subsetMemberships = subsetMemberships; } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/content/RetrieveAtomsTestCase.java ================================================ /*This example allows you to retrieve atoms for a known CUI or source-asserted identifier in the UMLS You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments in your runtime configuration, such as -Dapikey -Did=C0155502. To retrieve atoms that belong to a source-asserted concept, descriptor, or code, use the -Dsource parameter, such as -Dsource=SNOMEDCT_US */ package uts.rest.samples.content; import uts.rest.samples.classes.AtomLite; import uts.rest.samples.util.RestTicketClient; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import static com.jayway.restassured.RestAssured.given; import static org.junit.Assert.*; public class RetrieveAtomsTestCase { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); String id = System.getProperty("id"); String source = System.getProperty("source"); //specifying version is not required - if you leave it out the script will default to the latest UMLS publication. String version = System.getProperty("version"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); @Test public void RetrieveAtoms() throws Exception { version = System.getProperty("version") == null ? "current": System.getProperty("version"); //if you do not specify a source vocabulary, the script assumes you're searching for CUI String path = System.getProperty("source") == null ? "/rest/content/"+version+"/CUI/"+id+"/atoms" : "/rest/content/"+version+"/source/"+source+"/"+id+"/atoms"; AtomLite[] atoms; int page = 1; int pageCount; int numberOfAtoms = 0; //UMLS CUI may have hundreds of atoms, so we've set up a way to page through them here. do { System.out.println("Page "+page); System.out.println("***********"); RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; Response response = given()//.log().all() .request().with() //we need a new service ticket for each call since we're requesting multiple pages. .param("ticket", ticketClient.getST(tgt)) //.param("language", "ENG") //.param("ttys","PT") //.param("sabs","SNOMEDCT_US") .param("pageNumber",page) .expect() .statusCode(200) .when().get(path); //response.then().log().all();; String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); pageCount = JsonPath.using(config).parse(output).read("$.pageCount"); atoms = JsonPath.using(config).parse(output).read("$.result",AtomLite[].class); for(AtomLite atom:atoms) { System.out.println("AUI: "+ atom.getUi()); System.out.println("Name: " + atom.getName()); System.out.println("Term Type: " + atom.getTermType()); System.out.println("Obsolete: " + atom.getObsolete()); System.out.println("Vocabulary: " + atom.getRootSource()); System.out.println("UMLS Concept: " + atom.getConcept()); System.out.println("Source Concept: " + atom.getSourceConcept()); System.out.println("Source Descriptor: " + atom.getSourceDescriptor()); System.out.println("Source Code: " + atom.getCode()); System.out.println("-------"); } numberOfAtoms += atoms.length; page++; assertTrue(atoms.length > 0); } while(page <= pageCount ); System.out.println("Retrieved " + numberOfAtoms +" atoms for " + id); } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/content/RetrieveCodeTestCase.java ================================================ /*This example allows you to retrieve information about a known source-asserted identifier. You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments in your runtime configuration, such as -Dapikey -Did=9468002 -Dsource=SNOMEDCT_US */ package uts.rest.samples.content; import uts.rest.samples.util.RestTicketClient; import uts.rest.samples.classes.SourceAtomClusterLite; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import static com.jayway.restassured.RestAssured.given; import static org.apache.commons.lang.StringUtils.join; public class RetrieveCodeTestCase { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); String id = System.getProperty("id"); String version = System.getProperty("version"); String source = System.getProperty("source"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); @Test public void RetrieveCodes() throws Exception { //if you omit the -Dversion parameter, use 'current' as the default. version = System.getProperty("version") == null ? "current": System.getProperty("version"); String path = "/rest/content/"+version+"/source/"+source+"/"+id; RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; Response response = given().log().all() .request().with() .param("ticket", ticketClient.getST(tgt)) .expect() .statusCode(200) .when().get(path); //response.then().log().all();; String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); SourceAtomClusterLite code = JsonPath.using(config).parse(output).read("$.result",SourceAtomClusterLite.class); System.out.println(source+" code: " +code.getUi()+": "+code.getName()); System.out.println("Number of Atoms: " + code.getAtomCount()); System.out.println("Atoms: "+code.getAtoms()); System.out.println("Relations: "+code.getRelations()); System.out.println("Parents: "+code.getParents()); System.out.println("Children: "+code.getChildren()); System.out.println("Ancestors: "+code.getAncestors()); System.out.println("Descendants: "+code.getDescendants()); System.out.println("Highest Ranking Atom: "+code.getDefaultPreferredAtom()); } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/content/RetrieveCuiTestCase.java ================================================ /*This example allows you to retrieve information about a known UMLS CUI. Examples are at https://github.com/jayway/rest-assured/tree/master/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments in your runtime configuration, such as -Dapikey=12345-abcdef -Did=C0018787 */ package uts.rest.samples.content; import uts.rest.samples.util.RestTicketClient; import uts.rest.samples.classes.ConceptLite; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import static com.jayway.restassured.RestAssured.given; import static org.apache.commons.lang.StringUtils.join; public class RetrieveCuiTestCase { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); String id = System.getProperty("id"); String version = System.getProperty("version"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); @Test public void RetrieveCui() throws Exception { //if you omit the -Dversion parameter, use 'current' as the default. version = System.getProperty("version") == null ? "current": System.getProperty("version"); String path = "/rest/content/"+version+"/CUI/"+id; RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; Response response = given().log().all() .request().with() .param("ticket", ticketClient.getST(tgt)) .expect() .statusCode(200) .when().get(path); //response.then().log().all();; String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); ConceptLite conceptLite = JsonPath.using(config).parse(output).read("$.result",ConceptLite.class); System.out.println(conceptLite.getUi()+": "+conceptLite.getName()); System.out.println("Semantic Type(s): "+ join(conceptLite.getSemanticTypes(),",")); System.out.println("Number of Atoms: " + conceptLite.getAtomCount()); System.out.println("Atoms: "+conceptLite.getAtoms()); System.out.println("Definitions: "+conceptLite.getDefinitions()); System.out.println("Relations: "+conceptLite.getRelations()); System.out.println("Highest Ranking Atom: "+conceptLite.getDefaultPreferredAtom()); } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/content/WalkHierarchyTestCase.java ================================================ package uts.rest.samples.content; import uts.rest.samples.classes.AtomLite; import uts.rest.samples.classes.SourceAtomClusterLite; import uts.rest.samples.util.RestTicketClient; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import static com.jayway.restassured.RestAssured.given; import static org.junit.Assert.*; public class WalkHierarchyTestCase { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); String id = System.getProperty("id"); String source = System.getProperty("source"); //specifying version is not required - if you leave it out the script will default to the latest UMLS publication. String version = System.getProperty("version"); //use either 'parents', 'children', 'ancestors', or 'descendants' here String operation = System.getProperty("operation"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); @Test public void WalkHierarchy() throws Exception { version = System.getProperty("version") == null ? "current": System.getProperty("version"); //if you do not specify a source vocabulary, the script assumes you're searching for CUI String path = "/rest/content/"+version+"/source/"+source+"/"+id+"/"+operation; SourceAtomClusterLite[] sourceAtomClusters; AtomLite[] atoms; int page=1; int results = 0; int pageCount; //calls to descendants may produce several hundred or even several thousand results. //so we page through them here. do { System.out.println("Page "+page); System.out.println("***********"); RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; Response response = given()//.log().all() .request().with() //we need a new service ticket for each call since we're requesting multiple pages. .param("ticket", ticketClient.getST(tgt)) .param("pageNumber",page) .expect() .statusCode(200) .when().get(path); //response.then().log().all();; String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); pageCount = JsonPath.using(config).parse(output).read("$.pageCount"); //the HL7 sources return Atom objects, rather than SourceAtomClusters if(source.equals("HL7V3.0") || source.equals("HL7V2.5")) { atoms = JsonPath.using(config).parse(output).read("$.result",AtomLite[].class); for (AtomLite atom:atoms) { System.out.println("Ui: " + atom.getUi()); System.out.println("Name: "+ atom.getName()); System.out.println("Code: " + atom.getCode()); System.out.println("Parents: "+ atom.getParents()); System.out.println("Children: " + atom.getChildren()); System.out.println("-------"); } results += atoms.length; } else { sourceAtomClusters = JsonPath.using(config).parse(output).read("$.result",SourceAtomClusterLite[].class); for(SourceAtomClusterLite sourceAtomCluster:sourceAtomClusters) { System.out.println("Ui: "+sourceAtomCluster.getUi()); System.out.println("Name: "+sourceAtomCluster.getName()); System.out.println("Number of Atoms: "+sourceAtomCluster.getAtomCount()); System.out.println("Concepts: "+sourceAtomCluster.getConcepts()); System.out.println("Ancestors: "+sourceAtomCluster.getAncestors()); System.out.println("Parents: "+ sourceAtomCluster.getParents()); System.out.println("Children: "+sourceAtomCluster.getChildren()); System.out.println("Descendants: "+sourceAtomCluster.getDescendants()); System.out.println("Highest Ranking Atom: "+sourceAtomCluster.getDefaultPreferredAtom()); System.out.println("-------"); } results += sourceAtomClusters.length; } page++; //assertTrue(sourceAtomClusters.length > 0); } while(page <= pageCount ); System.out.println("Found " + results + " results"); } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/cookbook/CodeCrosswalk.java ================================================ /*This example loads a file of hpo identifiers(hpo-codes.txt from the 'resources' folder) * and retrieves SNOMED CT preferred terms * that live in the same UMLS CUI as the HPO identifier. */ package uts.rest.samples.cookbook; import java.io.BufferedReader; import java.io.FileReader; import uts.rest.samples.util.RestTicketClient; import uts.rest.samples.classes.*; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import static com.jayway.restassured.RestAssured.given; public class CodeCrosswalk { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); String version = System.getProperty("version"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); SourceAtomClusterLite[] sourceAtomClusters; @Test public void RunCrosswalk() throws Exception { version = System.getProperty("version") == null ? "current": System.getProperty("version"); System.out.println("HPO Id|SNOMEDCT ConceptId|SNOMEDCT Name"); try (BufferedReader br = new BufferedReader(new FileReader("resources/hpo-codes.txt"))) { String hpo; while ((hpo = br.readLine()) != null) { try { sourceAtomClusters = CrossWalkCodes(hpo, "SNOMEDCT_US"); for (SourceAtomClusterLite sourceAtomCluster:sourceAtomClusters) { System.out.println(hpo+"|"+sourceAtomCluster.getUi()+"|"+ sourceAtomCluster.getName()); } } catch (Exception ex) { //cannot find a CUI-based match to SNOMED CT System.out.println(hpo + "||"); } } } } public SourceAtomClusterLite[] CrossWalkCodes(String code, String targetSource) { RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; String path = "/rest/crosswalk/"+version+"/source/HPO/"+code; Response response = given()//.log().all() .request().with() .param("ticket", ticketClient.getST(tgt)) .param("targetSource", "SNOMEDCT_US") .when().get(path); String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); sourceAtomClusters = JsonPath.using(config).parse(output).read("$.result",SourceAtomClusterLite[].class); return sourceAtomClusters; } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/search/BatchTermToCuiOrCodeTestCase.java ================================================ /*This example loads a file of disease names (findings.txt from the 'resources' folder) * and retrieves the relevant UMLS CUI(s) or source-asserted codes */ package uts.rest.samples.search; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import uts.rest.samples.util.RestTicketClient; import uts.rest.samples.classes.SearchResult; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import static com.jayway.restassured.RestAssured.given; public class BatchTermToCuiOrCodeTestCase { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); String version = System.getProperty("version"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); @Test public void RetrieveCuis() throws Exception { version = System.getProperty("version") == null ? "current": System.getProperty("version"); try (BufferedReader br = new BufferedReader(new FileReader("resources/findings.txt"))) { String line; while ((line = br.readLine()) != null) { List results = SearchTerm(line); if (results.size() == 0){System.out.println("No results for "+ line);} int num = 1; for(SearchResult result:results) { String cui = result.getUri(); String name = result.getName(); String rsab = result.getRootSource(); System.out.println("Result "+ num); System.out.println("cui:"+ cui); System.out.println("name:"+ name); System.out.println("Highest ranking source of cui:" + rsab); num++; } System.out.println("----------"); } } } public List SearchTerm(String term) throws Exception { version = System.getProperty("version") == null ? "current": System.getProperty("version"); int pageNumber = 0; SearchResult[] results; List holder = new ArrayList(); do { pageNumber++; RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; Response response = given()//.log().all() .request().with() .param("ticket", ticketClient.getST(tgt)) .param("string", term) .param("pageNumber",pageNumber) //uncomment below to return only CUIs that have at least one non-obsolete/non-suppressible atom (relevant to the searchType) from the US Edition of SNOMED CT //.param("sabs","SNOMEDCT_US") //uncomment below to return CUIs that have at least one non-obsolete/non-suppressible atom that is an exact match with the search term //.param("searchType","exact") //valid values are exact,words, approximate,leftTruncation,rightTruncation, and normalizedString //uncomment below to return source-asserted identifiers (from SNOMEDCT and other UMLS vocabularies) instead of CUIs //.param("returnIdType","code") .expect() .statusCode(200) .when().get("/rest/search/"+version); String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); results = JsonPath.using(config).parse(output).read("$.result.results",SearchResult[].class); //the /search endpoint returns an array of 'result' objects //See http://documentation.uts.nlm.nih.gov/rest/search/index.html#sample-output for a complete list of fields output under the /search endpoint for(SearchResult result:results) { if (!results[0].getUi().equals("NONE")){holder.add(result);} } }while(!results[0].getUi().equals("NONE")); return holder; } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/search/SearchTermsTestCase.java ================================================ package uts.rest.samples.search; import uts.rest.samples.classes.SearchResult; import uts.rest.samples.util.RestTicketClient; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.junit.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.path.json.JsonPath.with; import static com.jayway.jsonpath.JsonPath.read; /*This example allows you to search terms in the UMLS Examples are at https://github.com/jayway/rest-assured/tree/master/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java For convenience, google's quick json parser is also included in the pom.xml file: https://code.google.com/p/quick-json/ You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments You may page through results returned from the /search endpoint until you reach the null 'ui:NONE' or 'name:NO RESULTS'. These results will always be a single result on their own page. in your runtime configuration, such as -Dapikey -Dterm = "diabetic foot" */ public class SearchTermsTestCase { //String username = System.getProperty("username"); //String password = System.getProperty("password"); String apiKey = System.getProperty("apikey"); //version is not a required argument - if left out you will search against the latest UMLS publication String version = System.getProperty("version"); String term = System.getProperty("term"); RestTicketClient ticketClient = new RestTicketClient(apiKey); //get a ticket granting ticket for this session. String tgt = ticketClient.getTgt(); @Test public void SearchTerm() throws Exception { version = System.getProperty("version") == null ? "current": System.getProperty("version"); int total = 0; int pageNumber = 0; SearchResult[] results; do { pageNumber++; System.out.println("Fetching results for page "+pageNumber); RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; Response response = given()//.log().all() .request().with() .param("ticket", ticketClient.getST(tgt)) .param("string", term) .param("pageNumber",pageNumber) //uncomment to return CUIs that have at least one matching term from the US Edition of SNOMED CT //.param("sabs", "SNOMEDCT_US") //uncomment to return SNOMED CT concepts rather than UMLS CUIs. //.param("returnIdType", "sourceConcept") //.param("searchType","exact") //valid values are exact,words, approximate,leftTruncation,rightTruncation, and normalizedString .expect() .statusCode(200) .when().get("/rest/search/"+version); String output = response.getBody().asString(); Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); results = JsonPath.using(config).parse(output).read("$.result.results",SearchResult[].class); //the /search endpoint returns an array of 'result' objects //See http://documentation.uts.nlm.nih.gov/rest/search/index.html#sample-output for a complete list of fields output under the /search endpoint for(SearchResult result:results) { String ui = result.getUi(); String name = result.getName(); String rootSource = result.getRootSource(); String uri = result.getUri(); System.out.println("ui: " + ui); System.out.println("name: " + name); System.out.println("rootSource: " + rootSource); System.out.println("uri: " + uri); System.out.println("**"); } System.out.println("----------"); total += results.length; }while(!results[0].getUi().equals("NONE")); //account for the one 'NO RESULTS' result :-/ total--; System.out.println("Found " + total+ " results for "+ term); } } ================================================ FILE: samples/java/src/test/java/uts/rest/samples/util/RestTicketClient.java ================================================ package uts.rest.samples.util; import static com.jayway.restassured.RestAssured.given; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Headers; import com.jayway.restassured.response.Response; public class RestTicketClient { private String tgt; private String st; private String service = "http://umlsks.nlm.nih.gov"; private String username = null; private String password = null; private String authUri = "https://utslogin.nlm.nih.gov"; private String apikey = null; public RestTicketClient (String username, String password) { this.username = username; this.password = password; } public RestTicketClient (String apikey) { this.apikey = apikey; } public String getTgt() { String tgt = null; if(this.username != null && this.password != null){ RestAssured.baseURI=authUri; Response response = given()//.log().all() .request().with() .param("username", username) .param("password", password) .expect() .statusCode(201) .when().post("/cas/v1/tickets"); Headers h = response.getHeaders(); tgt = h.getValue("location").substring(h.getValue("location").indexOf("TGT")); //response.then().log() } else if (apikey != null) { RestAssured.baseURI=authUri; Response response = given()//.log().all() .request().with() .param("apikey", apikey) .expect() .statusCode(201) .when().post("/cas/v1/api-key"); Headers h = response.getHeaders(); tgt = h.getValue("location").substring(h.getValue("location").indexOf("TGT")); } return tgt; } public String getST(String tgt) { RestAssured.baseURI=authUri; Response response = given()//.log().all() .request().with() .param("service", service) .expect() .statusCode(200) .when().post("/cas/v1/tickets/" + tgt); String st = response.getBody().asString(); //response.then().log().all(); return st; } public void logout(String ticket) { RestAssured.baseURI=authUri; Response response = given()//.log().all() .request().with() .param("service", service) .expect() .statusCode(200) .when().delete("/cas/v1/tickets/" + ticket); // response.then().log().all(); } } ================================================ FILE: samples/perl/crosswalk.pl ================================================ #!/usr/bin/perl -w ## usage: perl crosswalk.pl -u your-umls-username -p your-umls-password -v source vocabulary -i source vocabulary identifier [ -r specify target vocabulary] ## Performs a crosswalk using the latest UMLS version and retrieves all codes that share a UMLS CUI with a particular code. ## Example: ## perl crosswalk.pl -u username -p password -v HPO -i HP:0001947 ## perl crosswalk.pl -u username -p password -v HPO -i HP:0001947 -r SNOMEDCT_US ## More information: https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/crosswalk/index.html use lib "lib"; use strict; use URI; use Authentication::TicketClient; use JSON; use REST::Client; use Data::Dumper; use Getopt::Std; ## parse command line arguments our ($opt_u,$opt_p,$opt_v,$opt_i, $opt_r); getopt('upvir'); my $username = $opt_u || die "please provide username"; my $password = $opt_p || die "please provide password"; my $source = $opt_v || die "Please provide a source vocabulary"; my $identifier = $opt_i || die "Please provide a source vocabulary identifier"; ## Create a ticket granting ticket for the session my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; my $tgt = $ticketClient->getTgt(); my $uri = new URI("https://uts-ws.nlm.nih.gov"); my $json; my $client = REST::Client->new(); my %parameters = (); my $path = sprintf("/rest/crosswalk/current/source/%s/%s", $opt_v, $opt_i); if ( defined $opt_r && $opt_r ){ $parameters{'targetSource'} = $opt_r } ## Query the API $json = run_query($path,\%parameters); my $ra_results = $json->{'result'}; ## Loop through results foreach my $result( @$ra_results ) { printf("%s %s %s\n", $result->{'rootSource'}, $result->{'ui'}, $result->{'name'} ) } sub format_json { my $json_in = shift; my $json = JSON->new; my $obj = $json->decode($json_in); return $obj; } sub run_query { my ($path, $parameters) = @_; $parameters{ticket} = $ticketClient->getServiceTicket(); $uri->path($path); $uri->query_form($parameters); print qq{$uri\n\n}; my $query = $client->GET($uri) || die "Could not execute query $!\n"; my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query $!\n"; my $json = format_json($results); return $json; } ================================================ FILE: samples/perl/lib/Authentication/TicketClient.pm ================================================ ############################################################################################################################## # Version 1.0 - 7/28/2015 # The ticket client has two methods: # getTgt() and getServiceTicket() # run getTgt() to obtain your ticket granting ticket. # run getServiceTicket() before each call to https://uts-ws.nlm.nih.gov/rest/content or other future endpoints... to obtain a service ticket # in your client script, include the line use Authentication::TicketClient; # make a new ticket client as follows: # my $ticketClient = new TicketClient(username=>"yourusername",password=>"yourpassword",service=>"http://umlsks.nlm.nih.gov",tgt=>""); ############################################################################################################################## use warnings; use LWP::UserAgent; use URI; use HTML::Form; package TicketClient; sub new { my ($class,%args) = @_; return bless { %args }, $class; } sub getTgt { my $self = shift; my $uri = URI->new("https://utslogin.nlm.nih.gov"); my $ua = LWP::UserAgent->new; $uri->path("/cas/v1/tickets"); my $query = $ua->post($uri, ['username'=>$self->{username}, 'password'=>$self->{password} ],); die "Error: ", $query->status_line unless $query->is_success; my @forms = HTML::Form->parse($query); my $form = $forms[0]; my $tgtUrl = $form->action; ##actually here we're not getting just the TGT, but the entire URL from the action attribute of the form ##returned in the call. This saves us from having to extract the TGT with substr or something else. ##assign the action attribute URL to the 'tgt' property of the TicketClient. $self->{tgt} = $tgtUrl; }## end getTgt sub getServiceTicket { my $self = shift; my $ua = LWP::UserAgent->new; my $uri = URI->new($self->{tgt}); my $query = $ua->post($uri, ['service'=>$self->{service} ],); die "Error: ", $query->status_line unless $query->is_success; my $st = $query->content; return $st; } ## end getServiceTicket 1; ================================================ FILE: samples/perl/retrieve-atoms.pl ================================================ #!/usr/bin/perl ## Compatible with UMLS REST API - version 0.51 Beta ## usage: perl retrieve-atoms.pl -u your-umls-username -p your-umls-password -v version (optional) -i identifier -s source_vocabulary(optional) ## If you do not provide the version parameter the script queries the latest avaialble UMLS publication. ## This file takes a CUI or a source asserted identifier and retrieves atoms according to your query parameters. ## Use the -s flag to specify (optionally) a UMLS source vocabulary. If you omit this flag the script expects that your -i (identifier) argument will be ## populated with a UMLS CUI. ## The full list of fields available for search results is at https://documentation.uts.nlm.nih.gov/rest/atoms/index.html use lib "lib"; use strict; use warnings; use URI; use Authentication::TicketClient; use JSON; use REST::Client; use Data::Dumper; use Getopt::Std; our ($opt_u,$opt_p,$opt_v,$opt_i,$opt_s); getopt('upvsi'); my $username = $opt_u || die "please provide username"; my $password = $opt_p || die "please provide password"; my $version = defined $opt_v ? $opt_v : "current"; my $source = $opt_s; my $id = $opt_i || die "please provide an identifier"; ##create a ticket granting ticket for the session my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; my $tgt = $ticketClient->getTgt(); my $uri = new URI("https://uts-ws.nlm.nih.gov"); my $json; my $client = REST::Client->new(); my $pageNum = 1; my $pageCount; my $resultCount = 0; my %parameters = (); my $obj; my $path = defined $source ? "/rest/content/".$version."/source/".$source."/".$id."/atoms": "/rest/content/".$version."/CUI/".$id."/atoms" ; my $result; ## with /atoms you may get more than the default 25 objects per page. You can either set your paging to higher values or page through results ## as in this example. do { $parameters{pageNumber} = $pageNum; #$parameters{sabs} = "SNOMEDCT_US"; $parameters{language} = "ENG"; ##suppressible/obsolete atoms are excluded by default #$parameters{includeSuppressible} = "true"; #$parameters{includeObsolete} = "true"; #$parameters{ttys} = "PT"; $json = run_query($path,\%parameters); $pageCount = $json->{pageCount}; print qq{On page $pageCount of $pageNum pages\n}; foreach my $atom(@{ $json->{result} }) { printf "%s\n","AUI: ".$atom->{ui}; printf "%s\n","Atom Name: ".$atom->{name}; printf "%s\n","Language: ".$atom->{language}; printf "%s\n","Term Type: ".$atom->{termType}; printf "%s\n","Obsolete: ".$atom->{obsolete}; printf "%s\n","Suppressible: ".$atom->{suppressible}; printf "%s\n", "Source: ".$atom->{rootSource}; printf "%s\n", "CUI: " .$atom->{memberships}->{concept}; ## The {memberships} wrapper returned by the /atoms endpoint contains information about to which source concept,code,or source descriptor the atom belongs ## not all vocabularies have source descriptors or source concepts, so we make sure they exist. printf "%s\n", "Source Concept: " .$atom->{memberships}->{sourceConcept} if defined $atom->{memberships}->{sourceConcept}; printf "%s\n", "Source Descriptor: " .$atom->{memberships}->{sourceDescriptor} if defined $atom->{memberships}->{sourceDescriptor}; printf "%s\n", "Code: " .$atom->{memberships}->{code} if defined $atom->{memberships}->{code}; print qq{\n}; } print qq{-------\n}; $pageNum++; $resultCount += scalar((@{ $json->{result} })); } ##page all the way through until the end. while ($pageNum < ($pageCount + 1)); print qq{Found $resultCount total results\n}; sub format_json { my $json_in = shift; my $json = JSON->new; my $obj = $json->decode($json_in); #print Dumper(\$obj); return $obj; } sub run_query { my ($path, $parameters) = @_; $parameters{ticket} = $ticketClient->getServiceTicket(); $uri->path($path); $uri->query_form($parameters); print qq{$uri\n\n}; my $query = $client->GET($uri) || die "Could not execute query$!"; my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query$!"; my $json = format_json($results); return $json; } ================================================ FILE: samples/perl/retrieve-cui-or-code.pl ================================================ #!/usr/bin/perl ## Compatible with UMLS REST API - version 0.60 Beta ## This file retrieves basic information of a source-asserted identifer or UMLS CUI. ## usage: perl retrieve-concept-info.pl -u your-umls-username -p your-umls-password -v version -i identifer -s source vocabulary ## If you do not provide the version parameter the script queries the latest avaialble UMLS publication. ## To query the UMLS, omit the 'source' parameter and use UMLS CUI as your 'identifier' parameter. ## The full list of query parameters and fields available for CUI retrieval is at: ## https://documentation.uts.nlm.nih.gov/rest/concept/index.html and ## https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html use lib "lib"; use strict; use warnings; use URI; use Authentication::TicketClient; use JSON; use REST::Client; use Data::Dumper; use Getopt::Std; our ($opt_u,$opt_p,$opt_v,$opt_s, $opt_i); getopt('upvsi'); my $username = $opt_u || die "please provide username"; my $password = $opt_p || die "please provide password"; my $id = $opt_i || die "please provide a UMLS CUI or source-asserted identifier"; my $version = defined $opt_v ? $opt_v : "current"; my $source = $opt_s; ##create a ticket granting ticket for the session my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; my $tgt = $ticketClient->getTgt(); my $uri = new URI("https://uts-ws.nlm.nih.gov"); my %parameters = (); my $client = REST::Client->new(); my $path = defined $source ? "/rest/content/".$version."/source/".$source."/".$id : "/rest/content/".$version."/CUI/".$id; my $json = run_query($path,\%parameters); my $cuiOrCode = $json->{result}; printf "%s\n","ui- ".$cuiOrCode->{ui}; printf "%s\n","Number of Atoms- ".$cuiOrCode->{atomCount}; printf "%s\n","Name- ".$cuiOrCode->{name}; printf "%s\n","Atoms- ".$cuiOrCode->{atoms}; printf "%s\n","Definitions- ".$cuiOrCode->{definitions}; printf "%s\n","Relations- ".$cuiOrCode->{relations}; printf "%s\n","Highest Ranking Atom- ".$cuiOrCode->{defaultPreferredAtom}; my $stys = $cuiOrCode->{semanticTypes}; ## Semantic Types are only assigned to UMLS CUIs. There are often more than one semantic type per CUI. if (!defined $source) { printf "%s\n", "Semantic Types:"; foreach my $sty (@{ $stys }) { printf "%s\n", "uri: ".$sty->{uri}; printf "%s\n", "name: ".$sty->{name}; } } ##source-asserted data. UMLS CUIs do not have transitive relations. printf "%s\n","Parents- ".$cuiOrCode->{parents} if defined $source; printf "%s\n","Children- ".$cuiOrCode->{children} if defined $source; printf "%s\n","Ancestors- ".$cuiOrCode->{ancestors} if defined $source; printf "%s\n","Descendants- ".$cuiOrCode->{descendants} if defined $source; sub format_json { my $json_in = shift; my $json = JSON->new; my $obj = $json->decode($json_in); #print Dumper(\$obj); return $obj; } sub run_query { my ($path, $parameters) = @_; $parameters{ticket} = $ticketClient->getServiceTicket(); $uri->path($path); $uri->query_form($parameters); print qq{$uri\n}; my $query = $client->GET($uri) || die "Could not execute query$!"; my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query$!"; my $json = format_json($results); return $json; } ================================================ FILE: samples/perl/search-terms.pl ================================================ #!/usr/bin/perl ##usage: perl search-terms.pl -u your-umls-username -p your-umls-password -v version -s string ##If you do not provide the version parameter the script queries the latest avaialble UMLS publication. ##Use quotes if your search string has spaces, for example perl search-terms.pl -u username -p password -s "diabetic foot" ##This file searches the UMLS against a string you provide returns CUIs (by default) or source-asserted identifers. ##The full list of fields available for search results is at https://documentation.uts.nlm.nih.gov/rest/search/index.html use lib "lib"; use strict; use warnings; use URI; use Authentication::TicketClient; use JSON; use REST::Client; use Data::Dumper; use Getopt::Std; our ($opt_u,$opt_p,$opt_v,$opt_s); getopt('upvs'); my $username = $opt_u || die "please provide username"; my $password = $opt_p || die "please provide password"; my $version = defined $opt_v ? $opt_v : "current"; my $string = $opt_s || die "please provide a query string"; my $resultCount = 0; ##create a ticket granting ticket for the session my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; my $tgt = $ticketClient->getTgt(); my $uri = new URI("https://uts-ws.nlm.nih.gov"); my $json; my $client = REST::Client->new(); my %parameters = (); my $pageNum = "1"; my $path = "/rest/search/".$version; $parameters{string} = $string; #$parameters{searchType} = "exact"; ##optional parameters to return source-asserted identifiers and filter by source. You can also use 'sourceConcept' (for SNOMEDCT_US, LNC, NCI,RXNORM) or 'sourceDescriptor' (for MSH,MDR,ICD9CM,ICD10CM,GO) #$parameters{returnIdType} = "code"; $parameters{sabs} = "SNOMEDCT_US"; print qq{Searching term $string\n}; #many term searches will return more than the default page size, which is 25 json objects, so we page through them here. do { $parameters{pageNumber} = $pageNum; #$parameters{pageSize} = "10"; print qq{Page $pageNum Results\n}; $json = run_query($path,\%parameters); foreach my $result(@{ $json->{result}{results} }) { printf "%s\n","uri: ".$result->{uri} if defined $result->{uri}; printf "%s\n","ui: ".$result->{ui} if $result->{ui} ne 'NONE'; printf "%s\n","name: ".$result->{name} if $result->{name} ne 'NO RESULTS'; printf "%s\n","Source Vocabulary: ".$result->{rootSource} if defined $result->{rootSource}; print qq{\n}; } print qq{----------\n}; $pageNum++; $resultCount+= scalar(@{ $json->{result}{results} }); } ##TODO: Add 'next' and 'previous' page URIs to JSON output so we don't have to do this:. while $json->{result}{results}[0]{name} ne 'NO RESULTS'; ### paging is not fully implemented under the /search endpoint, so we have to discount the one 'NO RESULTS' result. $resultCount--; print qq{Found $resultCount results\n}; sub format_json { my $json_in = shift; my $json = JSON->new; my $obj = $json->decode($json_in); #print Dumper(\$obj); return $obj; } sub run_query { my ($path, $parameters) = @_; $parameters{ticket} = $ticketClient->getServiceTicket(); $uri->path($path); $uri->query_form($parameters); print qq{$uri\n\n}; my $query = $client->GET($uri) || die "Could not execute query $!\n"; my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query $!\n"; my $json = format_json($results); return $json; } ================================================ FILE: samples/perl/walk-hierarchy.pl ================================================ #!/usr/bin/perl ## Compatible with UTS REST API - version 0.51 Beta ## This file retrieves allows you to retrieve parents, children, ancestors, or descendants of a source-asserted concept, descriptor, or code. ## usage: perl retrieve-concept-info.pl -u your-umls-username -p your-umls-password -v version -i identifer -s source vocabulary ## If you do not provide the version parameter the script queries the latest avaialble UMLS publication. ## The full list of query parameters and fields available for source-asserted data retrieval is at: ## https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html use lib "lib"; use strict; use warnings; use URI; use Authentication::TicketClient; use JSON; use REST::Client; use Data::Dumper; use Getopt::Std; our ($opt_u,$opt_p,$opt_v,$opt_s, $opt_i,$opt_o); getopt('upvsio'); my $username = $opt_u || die "please provide username"; my $password = $opt_p || die "please provide password"; my $version = defined $opt_v ? $opt_v : "current"; my $source = $opt_s || die "please provide a source vocabulary, such as SNOMEDCT_US"; my $id = $opt_i || die "please provide a source-asserted identifier"; my $operation = $opt_o || die "please specify 'children', 'ancestors', 'descendants', or 'parents'"; my $json; my $pageNum = 1; my $pageCount; my $resultCount = 0; ##create a ticket granting ticket for the session my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; my $tgt = $ticketClient->getTgt(); my $uri = new URI("https://uts-ws.nlm.nih.gov"); my %parameters = (); my $client = REST::Client->new(); my $path = "/rest/content/".$version."/source/".$source."/".$id."/".$operation; do { $parameters{pageNumber} = $pageNum; $json = run_query($path,\%parameters); $pageCount = $json->{pageCount}; print qq{On page $pageNum of $pageCount pages\n}; foreach my $ui (@{ $json->{result} }) { printf "%s\n","ui- ".$ui->{ui}; printf "%s\n","Name- ".$ui->{name}; printf "%s\n","Atoms- ".$ui->{atoms}; printf "%s\n","Highest Ranking Atom- ".$ui->{defaultPreferredAtom}; printf "%s\n","Parents - ".$ui->{parents}; printf "%s\n","Children- ".$ui->{children}; printf "%s\n","Ancestors- ".$ui->{ancestors}; printf "%s\n","Descendants- ".$ui->{descendants}; printf "%s\n","Obsolete- ".$ui->{obsolete}; print qq{\n}; } print qq{-------\n}; $pageNum++; $resultCount += scalar(@{$json->{result}}); } while ($pageNum < ($pageCount + 1)); print qq{Found $resultCount total results\n}; sub format_json { my $json_in = shift; my $json = JSON->new; my $obj = $json->decode($json_in); #print Dumper(\$obj); return $obj; } sub run_query { my ($path, $parameters) = @_; $parameters{ticket} = $ticketClient->getServiceTicket(); $uri->path($path); $uri->query_form($parameters); print qq{$uri\n}; my $query = $client->GET($uri) || die "Could not execute query$!"; my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query$!"; my $json = format_json($results); return $json; } ================================================ FILE: samples/python/Authentication.py ================================================ #!/usr/bin/python ## 6/16/2017 - remove PyQuery dependency ## 5/19/2016 - update to allow for authentication based on api-key, rather than username/pw ## See https://documentation.uts.nlm.nih.gov/rest/authentication.html for full explanation import requests #from pyquery import PyQuery as pq import lxml.html as lh from lxml.html import fromstring uri="https://utslogin.nlm.nih.gov" #option 1 - username/pw authentication at /cas/v1/tickets #auth_endpoint = "/cas/v1/tickets/" #option 2 - api key authentication at /cas/v1/api-key auth_endpoint = "/cas/v1/api-key" class Authentication: #def __init__(self, username,password): def __init__(self, apikey): #self.username=username #self.password=password self.apikey=apikey self.service="http://umlsks.nlm.nih.gov" def gettgt(self): #params = {'username': self.username,'password': self.password} params = {'apikey': self.apikey} h = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-Agent":"python" } r = requests.post(uri+auth_endpoint,data=params,headers=h) response = fromstring(r.text) ## extract the entire URL needed from the HTML form (action attribute) returned - looks similar to https://utslogin.nlm.nih.gov/cas/v1/tickets/TGT-36471-aYqNLN2rFIJPXKzxwdTNC5ZT7z3B3cTAKfSc5ndHQcUxeaDOLN-cas ## we make a POST call to this URL in the getst method tgt = response.xpath('//form/@action')[0] return tgt def getst(self,tgt): params = {'service': self.service} h = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-Agent":"python" } r = requests.post(tgt,data=params,headers=h) st = r.text return st ================================================ FILE: samples/python/crosswalk.py ================================================ ## Steven Emrick - steve.emrick@nih.gov ## usage: python crosswalk.py -k ## You can specify a specific UMLS version with the -v argument, but it is not required ## This reads a file with codes from the Human Phenotype Ontology and maps them to the US Edition of SNOMED CT through UMLS CUIs from __future__ import print_function from Authentication import * import requests import json import argparse import collections import sys import os if sys.version_info < (3, 0): reload(sys) sys.setdefaultencoding('utf-8') parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") args = parser.parse_args() apikey = args.apikey version = args.version AuthClient = Authentication(apikey) ################################### #get TGT for our session ################################### tgt = AuthClient.gettgt() base_uri = "https://uts-ws.nlm.nih.gov" crosswalk_endpoint = "/rest/crosswalk/"+version+"/source/HPO" def crosswalk_code(path): query = {'ticket': AuthClient.getst(tgt),'targetSource': 'SNOMEDCT_US'} r = requests.get(base_uri + path, params=query) #print(r.url + "\n") items = json.loads(r.text) return items with open('hpo-codes.txt','r') as f: for line in f: ##get rid of newlines code = line.strip() path = crosswalk_endpoint+"/"+code try: results = crosswalk_code(path) for sourceAtomCluster in results["result"]: print('HPO Code - ' + code+ '\t' + 'SNOMEDCT concept -- ' + sourceAtomCluster["ui"] + ': ' + sourceAtomCluster["name"]) except ValueError: print("No result found for "+code) pass f.close() ================================================ FILE: samples/python/get-content-view-members.py ================================================ ## usage: python get-content-view-members.py -k -f ## You can specify a specific UMLS version with the -v argument, but it is not required ## This script will download the CORE Problem List subset of SNOMED CT ## and save to a file that you specify. There are around 250 pages of output to save - the CORE Problem list contains over 5,500 SNOMED CT codes ## and attributes. The script takes around 30 minutes to complete depending on your internet connection. from Authentication import * import requests import json import argparse import collections import sys reload(sys) sys.setdefaultencoding('utf-8') parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") parser.add_argument("-f", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") args = parser.parse_args() apikey = args.apikey version = args.version outputfile=args.outputfile AuthClient = Authentication(apikey) ################################### #get TGT for our session ################################### tgt = AuthClient.gettgt() base_uri = "https://uts-ws.nlm.nih.gov" #C2711988 is the CUI for the SNOMED CT CORE Problem List content view #Full list of content views is here: https://www.nlm.nih.gov/research/umls/knowledge_sources/metathesaurus/release/content_views.html, #or over web services at https://uts-ws.nlm.nih.gov/rest/content-views/current?ticket=ST... content_view_endpoint = "/rest/content-views/"+version+"/CUI/C2711988/members" tgt = AuthClient.gettgt() pageNumber=1 pageCount=1 f = open(outputfile, 'w') #column headers - modify accordingly if you are computing a different subset f.write("SNOMED_CID|NAME|FIRST_IN_SUBSET|IS_RETIRED_FROM_SUBSET|OCCURRENCE|USAGE|REPLACED_BY_SNOMED_CID\n") ##There are ~ 250 pages in this subset, if you're using the default of 25 objects per page. while pageNumber<=pageCount: query = {'ticket':AuthClient.getst(tgt),'pageNumber':pageNumber} r = requests.get(base_uri+content_view_endpoint,params=query) print(r.url+"\n") r.encoding = 'utf-8' items = json.loads(r.text) pageCount=items["pageCount"] print("Fetching page " + str(pageNumber)+" of results\n") for result in items["result"]: f.write(result["ui"]+"|"+str(result["name"])) #MOST CONTENT VIEW MEMBERS DO NOT HAVE ATTRIBUTES, BUT FOR MEMBERS OF THE SNOMED CT CORE PROBLEM LIST #THESE ARE THE CURRENT LIST OF ATTRIBUTE NAMES THAT ARE DEFINED. HOWEVER, IN THE DATA THEY ARE NOT ALWAYS PRESENT #FOR EXAMPLE, IF IS_RETIRED_FROM_SUBSET = True, THERE IS NO 'OCCURRENCE' OR 'USAGE' ATTRIBUTE AVAILABLE, SO WE MUST CHECK AND THEN ##OUTPUT EMPTY FIELDS IF NEEDED attributes=result["contentViewMemberAttributes"] if len(attributes) > 0: cv_member_attributes = (("FIRST_IN_SUBSET",""), ('IS_RETIRED_FROM_SUBSET', ""), ("OCCURRENCE", ""), ("USAGE", ""), ("REPLACED_BY_SNOMED_CID", "")) cv_member_attributes = collections.OrderedDict(cv_member_attributes) existing_attributes = {} f.write("|") for attribute in attributes: existing_attributes[attribute["name"]] = attribute["value"] for cv_member_attribute in cv_member_attributes.keys(): #populate the attributes that are presented to us in the json if cv_member_attribute in existing_attributes.keys(): cv_member_attributes[cv_member_attribute] = existing_attributes[cv_member_attribute] for i,item in enumerate(list(cv_member_attributes.items())): ##either print a delimiter or a new line depending on where we are in the list of attributes if i < len(list(cv_member_attributes.items())) - 1: f.write(item[1]+"|") else: f.write(item[1]+"\n") else: f.write("\n") pageNumber+=1 ================================================ FILE: samples/python/get-rxcui-ingredients.py ================================================ #This script takes a list of rxnorm normal forms and attempts to associate with a MIN,PIN, or IN #coding=utf-8 #get status of each rxcui #if active, get all ingredients (IN,MIN,PIN) #if there is a MIN, add that to the ingredients dictionary, ignore others #if there is a PIN, add that to the ingredients dictionary, ignore others #if only an IN exists add that to the ingredients dictionary ##at the end, for each IN, check and see if USP has a related salt form PIN via the UMLS API If so, remove the IN. import requests import json import argparse import simplejson import collections import sys import time from requests import utils from Authentication import * parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") uts = "https://uts-ws.nlm.nih.gov/" uri = "https://rxnav.nlm.nih.gov" #uri = "https://morc3.nlm.nih.gov" args = parser.parse_args() apikey = args.apikey inputfile=args.inputfile outputfile=args.outputfile ingredients = {} complete = False ################################### #get TGT for our session ################################### AuthClient = Authentication(apikey) tgt = AuthClient.gettgt() def get(path,query): try: time.sleep(.05) r = requests.get(uri+path, params=query, timeout=10) print(r.url) return simplejson.loads(r.text) except requests.exceptions.RequestException as e: print "Connection timing out..." sys.exit(1) def uts_get(path,query): r = requests.get(uts+path, params=query) print(r.url) if r.status_code == 404: #print "404" return "no usp atom" else: return simplejson.loads(r.text) def getRxCuiStatus(rxcui): path = "/REST/rxcui/"+rxcui+"/status.json" query = {} results = get(path,query) return results def checkIngredient(rxcui): path = "/REST/rxcui/"+rxcui+"/related.json?tty=IN+MIN+PIN" query = {} results=get(path,query) return results def getSaltFormCuis(rxcui): cuis = {} path = "/REST/rxcui/"+rxcui+"/related.json?tty=PIN" query = {} results=get(path,query) for group in results["relatedGroup"]["conceptGroup"]: try: for properties in group["conceptProperties"]: #print properties["rxcui"]+", "+ properties["name"] cuis[properties["rxcui"]] = {"rxcui":properties["rxcui"],"tty":properties["tty"],"name":properties["name"],"umlscui":properties["umlscui"]} except: KeyError #print cuis return cuis def checkForUspAtom(cui): path = "/rest/content/current/CUI/"+cui+"/atoms" query = {"sabs":"USPMG","ttys":"PT","ticket":AuthClient.getst(tgt)} results = uts_get(path,query) return results def parseIngredient(related): results = {} global complete complete = False for group in related["relatedGroup"]["conceptGroup"]: try: for properties in group["conceptProperties"]: #print properties["rxcui"]+", "+ properties["name"] results[group["tty"]] = {"rxcui":properties["rxcui"],"tty":properties["tty"],"name":properties["name"]} except: KeyError for tty in sorted(results.keys()): #print tty if "MIN" in results and complete == False: #print results["MIN"] if results["MIN"]["rxcui"] not in ingredients.keys(): ingredients[results["MIN"]["rxcui"]] = results["MIN"] complete = True elif "MIN" not in results and "PIN" in results and complete == False: #print results["PIN"] if results["PIN"]["rxcui"] not in ingredients.keys(): ingredients[results["PIN"]["rxcui"]] = results["PIN"] #print results["PIN"]["name"] complete = True elif "MIN" not in results and "PIN" not in results and results["IN"]["rxcui"] not in ingredients.keys() and complete == False: if results["IN"]["rxcui"] not in ingredients.keys(): ingredients[results["IN"]["rxcui"]] = results["IN"] complete = True with open(inputfile, 'r') as f: for line in f: rxcui = line.strip() json = getRxCuiStatus(rxcui) status = json["rxcuiStatus"]["status"].encode('utf-8') if status == "Active": related = checkIngredient(rxcui) parseIngredient(related) elif status == "Remapped" or status == "Quantified": for remapped in json["rxcuiStatus"]["minConceptGroup"]["minConcept"]: related = checkIngredient(remapped["rxcui"]) parseIngredient(related) f.close() w = open(outputfile, 'w') ##cleanup - remove INs that have a salt form with an exising USP atom, and add the USP salt form if it is not already in the ingredients dictionary for rxcui in ingredients.keys(): if ingredients[rxcui]["tty"] == "IN": saltFormCuis = getSaltFormCuis(rxcui) for pin in saltFormCuis.keys(): ##not all PINs in RxNorm will have UMLS CUIs #print saltFormCuis[pin] if saltFormCuis[pin]["umlscui"]: uspAtom = checkForUspAtom(saltFormCuis[pin]["umlscui"]) if uspAtom != "no usp atom" and rxcui in ingredients.iterkeys(): print "removing " + ingredients[rxcui]["name"] #remove the single ingredient form del ingredients[rxcui] #add the USP salt form if saltFormCuis[pin]["rxcui"] not in ingredients.iterkeys(): print "adding " + saltFormCuis[pin]["name"] #get rid of the UMLS CUI - we don't need it anymore del saltFormCuis[pin]["umlscui"] ingredients[rxcui] = saltFormCuis[pin] ##output results for rows in sorted(ingredients.values()): line = '|'.join(rows.values()) w.write(line+"\n") ================================================ FILE: samples/python/get-rxcui-status.py ================================================ #This script provides a way to query the RxNorm API to determine the status of an RxCUI #coding=utf-8 import requests import json import argparse import xml.etree.ElementTree as ET import simplejson import time import sys from urllib import unquote from requests import utils parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") uri = "https://morc3.nlm.nih.gov" args = parser.parse_args() inputfile=args.inputfile outputfile=args.outputfile def get(path,query): time.sleep(.05) r = requests.get(uri+path, params=query) print(r.url) return simplejson.loads(r.text) def getRxCuiStatus(rxcui): path = "/RxNormRest/rxcui/"+rxcui+"/status.json" query = {} results = get(path,query) return results w = open(outputfile, 'w') rxcuis = {} with open(inputfile, 'r') as f: for line in f: rxcui = line.strip() json = getRxCuiStatus(rxcui) status = json["rxcuiStatus"]["status"].encode('utf-8') if not status == "Active": if status == "Remapped" or status == "Quantified": #print rxcui +"\t" + status for remapped in json["rxcuiStatus"]["minConceptGroup"]["minConcept"]: print rxcui +"\t"+ status+"\t"+ remapped["rxcui"] rxcuis[rxcui] = {"rxcui":rxcui,"status":status,"remapped":remapped["rxcui"]} else: rxcuis[rxcui] = {"rxcui":rxcui,"status":status,"remapped":" "} #output for rows in sorted(rxcuis.values()): line = '|'.join(rows.values()) w.write(line+"\n") ================================================ FILE: samples/python/get-rxcuis-by-tty.py ================================================ #This script provides a way to query the RxNorm API for #prescribable drugs based on term types import requests import json import argparse import xml.etree.ElementTree as ET import sys from urllib import unquote from requests import utils parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-ttys", "--termtypes", required = True, dest = "ttys", help = "Enter TTYs to query, separated by a space") parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") uri = "https://rxnav.nlm.nih.gov" args = parser.parse_args() ttys = args.ttys outputfile=args.outputfile o = open(outputfile, 'w') def get(path,query): r = requests.get(uri+path, params=query) #print(r.url) return r.text.encode('utf-8') def getRxCuisByTermType(): path = "/REST/allconcepts" query = {'tty':ttys} results = get(path,query) return results def filterRxCuis(rxcui,filter): path = "/REST/rxcui/"+rxcui+"/filter" query = {'propName': filter} results = get(path,query) return results results = getRxCuisByTermType() xml = ET.fromstring(results) for rxcuis in xml.findall(".//minConcept"): rxcui = rxcuis.find("rxcui").text #now make sure the concept is part of the prescribable subset filtered = filterRxCuis(rxcui,'prescribable') rxnormdata = ET.fromstring(filtered) #only output if the concept belongs to the prescribable subset of RxNorm if len(rxnormdata) > 0: print rxnormdata.find('rxcui').text + " is prescribable" o.write(rxnormdata.find('rxcui').text+"\n") ================================================ FILE: samples/python/hpo-codes.txt ================================================ HP:0001735 HP:0001947 HP:0100631 HP:0001022 HP:0001596 HP:0000646 HP:0009916 HP:0100845 HP:0001102 HP:0000739 HP:0000787 HP:0011484 HP:0001871 HP:0030346 ================================================ FILE: samples/python/retrieve-cui-or-code.py ================================================ ################################################################################################# # usage of the script # usage: python retrieve-cui-or-code.py -k APIKEY -v VERSION -i IDENTIFIER -s SOURCE # If you do not provide the -s parameter, the script assumes you are retrieving information for a # known UMLS CUI ################################################################################################# from Authentication import * import requests import json import argparse parser = argparse.ArgumentParser(description='process user given parameters') #parser.add_argument("-u", "--username", required = True, dest="username", help = "enter username") #parser.add_argument("-p", "--password", required = True, dest="password", help = "enter passowrd") parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") parser.add_argument("-i", "--identifier", required = True, dest="identifier", help = "enter identifier example-C0018787") parser.add_argument("-s", "--source", required = False, dest="source", help = "enter source name if known") args = parser.parse_args() #username = args.username #password = args.password apikey = args.apikey version = args.version identifier = args.identifier source = args.source AuthClient = Authentication(apikey) ################################### #get TGT for our session ################################### tgt = AuthClient.gettgt() uri = "https://uts-ws.nlm.nih.gov" try: source except NameError: source = None ##if we don't specify a source vocabulary, assume we're retrieving UMLS CUIs if source is None: content_endpoint = "/rest/content/"+str(version)+"/CUI/"+str(identifier) else: content_endpoint = "/rest/content/"+str(version)+"/source/"+str(source)+"/"+str(identifier) ##ticket is the only parameter needed for this call - paging does not come into play because we're only asking for one Json object query = {'ticket':AuthClient.getst(tgt)} r = requests.get(uri+content_endpoint,params=query) r.encoding = 'utf-8' items = json.loads(r.text) jsonData = items["result"] ##uncomment the print statment if you want the raw json output, or you can just look at the documentation :=) #https://documentation.uts.nlm.nih.gov/rest/concept/index.html#sample-output #https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html#sample-output #print (json.dumps(items, indent = 4)) ############################ ### Print out fields #### classType = jsonData["classType"] name = jsonData["name"] ui = jsonData["ui"] AtomCount = jsonData["atomCount"] Definitions = jsonData["definitions"] Atoms = jsonData["atoms"] DefaultPreferredAtom = jsonData["defaultPreferredAtom"] ## print out the shared data elements that are common to both the 'Concept' and 'SourceAtomCluster' class print ("classType: " + classType) print ("ui: " + ui) print ("Name: " + name) print ("AtomCount: " + str(AtomCount)) print ("Atoms: " + Atoms) print ("Default Preferred Atom: " + DefaultPreferredAtom) ## These data elements may or may not exist depending on what class ('Concept' or 'SourceAtomCluster') you're dealing with so we check for each one. try: jsonData["definitions"] print ("definitions: " + jsonData["definitions"]) except: pass try: jsonData["parents"] print ("parents: " + jsonData["parents"]) except: pass try: jsonData["children"] print ("children: " + jsonData["children"]) except: pass try: jsonData["relations"] print ("relations: " + jsonData["relations"]) except: pass try: jsonData["descendants"] print ("descendants: " + jsonData["descendants"]) except: pass try: jsonData["semanticTypes"] print("Semantic Types:") for stys in jsonData["semanticTypes"]: print("uri: "+ stys["uri"]) print("name: "+ stys["name"]) except: pass ================================================ FILE: samples/python/retrieve-usp-atoms-from-umls.py ================================================ ###Takes a list of CUIs that result from /search?string=PT,IN,MIN,PIN&inputType=tty&sabs=RXNORM,USPMG. ###For each of theses CUIs, output the atoms ###If there is a PIN from RxNorm in the same CUI as a USPMG atom, find the RxNorm associated single ingredient form and ###remove it from the final list ###Then go through again and remove USP atoms that are in the same CUI as an RxNorm atom from Authentication import * import requests import simplejson import argparse import collections import sys from collections import OrderedDict reload(sys) sys.setdefaultencoding('utf-8') parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") parser.add_argument("-s", "--sabs", required = False, dest="sabs",help = "enter a comma-separated list of vocabularies, like MSH, SNOMEDCT_US, or RXNORM") parser.add_argument("-t", "--ttys", required = False, dest="ttys",help = "enter a comma-separated list of term types, like PT,SY,IN") parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") args = parser.parse_args() apikey = args.apikey version = args.version outputfile = args.outputfile inputfile = args.inputfile sabs = args.sabs ttys = args.ttys AuthClient = Authentication(apikey) ################################### #get TGT for our session ################################### tgt = AuthClient.gettgt() base_uri = "https://uts-ws.nlm.nih.gov" rxnorm = "https://rxnav.nlm.nih.gov" pageNumber=1 pageCount=1 auis = {} if outputfile: o = open(outputfile, 'w') def rxnorm_get(path,query): r = requests.get(rxnorm+path, params=query) print(r.url) return simplejson.loads(r.text) def uts_get(path,query): r = requests.get(base_uri+path, params=query) print(r.url) return simplejson.loads(r.text) def getSingleIngredientForm(rxcui): path = "/REST/rxcui/"+rxcui+"/related.json?tty=IN" query = {} #print(r.url) results=rxnorm_get(path,query) return results def retrieveConceptAtoms(cui): path = "/rest/content/"+version+"/CUI/"+cui+"/atoms" query = {"ticket":AuthClient.getst(tgt)} if sabs: query["sabs"] = sabs if ttys: query["ttys"] = ttys results = uts_get(path,query) return results with open(inputfile, 'r') as f: for line in f: cui = line.strip() json = retrieveConceptAtoms(cui) for atoms in json["result"]: slash = atoms["code"].rfind("/") code = atoms["code"][slash+1:] #rootSources[atoms["rootSource"]] = code+"\t"+atoms["termType"]+"\t"+atoms["name"] auis[atoms["ui"]] = {"cui":cui,"code":code,"tty":atoms["termType"],"name":atoms["name"],"sab":atoms["rootSource"]} f.close() ##Cleanup - find all PIN atoms in CUI with a USP atom ##Find related single ingredient form and remove it. singleIngredientCuis = [] ##identify PINS in the list of all atoms. ##If there is a PIN from RxNorm that shares a CUI with a USPMG atom, find the CUI of the IN form (/rxcui/related?tty=IN) and remove all ##atoms containing that CUI for aui1 in auis.keys(): print '|'.join(auis[aui1].values()) if auis[aui1]["tty"] == "PIN": print "Found salt form of " + auis[aui1]["cui"] + " " + auis[aui1]["name"] print "searching for " + auis[aui1]["code"] + " from " + auis[aui1]["sab"] for aui2 in auis.keys(): if auis[aui1]["cui"] == auis[aui2]["cui"] and auis[aui2]["sab"] == "USPMG": singleIngredients = getSingleIngredientForm(auis[aui1]["code"]) for properties in singleIngredients["relatedGroup"]["conceptGroup"][0]["conceptProperties"]: singleIngredientCuis.append(properties["umlscui"]) ## find the intersection of the 2 dictionaries, and delete the auis that represent single ingredients that already rels to USP salt form sameCuis = [auis[cui]["cui"] for cui in auis.keys() if auis[cui]["cui"] in singleIngredientCuis] print "Found " + str(len(auis)) + " total atoms in the result set\n" print "Found " +str(len(sameCuis)) + " CUIs with single ingredient atoms\n" for cui in auis.keys(): if auis[cui]["cui"] in sameCuis: print "removing " + auis[cui]["name"] del auis[cui] removals = [] log = open("removal-log.txt",'w') for cui1 in auis.keys(): for cui2 in auis.keys(): if auis[cui2]["sab"] == "RXNORM" and auis[cui1]["sab"] == "USPMG" and (auis[cui1]["cui"] == auis[cui2]["cui"]): print "Found " + cui1 + " and " + cui2 +" in " + auis[cui1]["cui"] #identify all USPMG atoms that are merged into the same UMLS CUI as an RxNorm atom removals.append(cui1) print "Removing " + str(len(removals)) + " USP atoms that share a CUI with RxNorm\n" for cui in auis.keys(): if cui in removals: line = '|'.join(auis[cui].values()) log.write(line+"\n") del auis[cui] print "Total of "+ str(len(auis)) + " atoms are left in results" w = open(outputfile, 'w') for fields in auis.values(): line = '|'.join(fields.values()) print line+"\n" w.write(line+"\n") ================================================ FILE: samples/python/retrieve-value-set-info.py ================================================ ###A script to retrieve code system information from the value set bps definition document. ###Note that the rows of the input file are expected to have the from Authentication import * import requests import json import argparse import xml.etree.ElementTree as ET import sys parser = argparse.ArgumentParser(description='process user given parameters') parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-p", "--profile", required = False, dest = "profile", help = "Enter a binding profile, such as MU2 2016 Update") parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") args = parser.parse_args() apikey = args.apikey profile = args.profile outputfile=args.outputfile inputfile=args.inputfile AuthClient = Authentication(apikey) tgt = AuthClient.gettgt() uri = "https://vsac.nlm.nih.gov/vsac/svs/RetrieveMultipleValueSets" o = open(outputfile, 'w') def getCodeSystem(id): ticket = AuthClient.getst(tgt) query = {'id':id,'ticket':ticket,'version':profile} r = requests.get(uri, params=query) print(r.url) return r.text.encode('utf-8') with open(inputfile,'r') as f: for line in f: oid,name,memberOid,memberOidName = line.strip().split("|") if len(memberOid) == 0: codeSystem = getCodeSystem(oid) else: codeSystem = getCodeSystem(memberOid) xml = ET.fromstring(codeSystem) ns = {"ns0":"urn:ihe:iti:svs:2008"} codeSystemInfo = {} for concepts in xml.findall(".//ns0:ConceptList/ns0:Concept",ns): cs = concepts.get('codeSystemName') codeSystemVersion = concepts.get('codeSystemVersion') codeSystemInfo.setdefault(cs,[]).append(codeSystemVersion) sys.stdout.write(oid+"|"+memberOid) for k,v in codeSystemInfo.items(): sys.stdout.write(k+"|"+','.join(set(v))) #o.write(oid+"|"+name+"|"+memberOid+"|"+k+"|"+','.join(set(v))) o.write(oid + "|" + name + "|" + memberOid + "|"+ memberOidName +"|" + k +"|"+','.join(set(v))+"\n") ================================================ FILE: samples/python/search-terms.py ================================================ ################################################################################# # usage of the script # usage: python search-terms.py -k APIKEY -v VERSION -s STRING # see https://documentation.uts.nlm.nih.gov/rest/search/index.html for full docs # on the /search endpoint ################################################################################# from __future__ import print_function from Authentication import * import requests import json import argparse parser = argparse.ArgumentParser(description='process user given parameters') #parser.add_argument("-u", "--username", required = True, dest="username", help = "enter username") #parser.add_argument("-p", "--password", required = True, dest="password", help = "enter passowrd") parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") parser.add_argument("-s", "--string", required = True, dest="string", help = "enter a search term, like 'diabetic foot'") args = parser.parse_args() #username = args.username #password = args.password apikey = args.apikey version = args.version string = args.string uri = "https://uts-ws.nlm.nih.gov" content_endpoint = "/rest/search/"+version ##get at ticket granting ticket for the session AuthClient = Authentication(apikey) tgt = AuthClient.gettgt() pageNumber=0 while True: ##generate a new service ticket for each page if needed ticket = AuthClient.getst(tgt) pageNumber += 1 query = {'string':string,'ticket':ticket, 'pageNumber':pageNumber} #query['includeObsolete'] = 'true' #query['includeSuppressible'] = 'true' #query['returnIdType'] = "sourceConcept" #query['sabs'] = "SNOMEDCT_US" r = requests.get(uri+content_endpoint,params=query) r.encoding = 'utf-8' items = json.loads(r.text) jsonData = items["result"] #print (json.dumps(items, indent = 4)) print("Results for page " + str(pageNumber)+"\n") for result in jsonData["results"]: try: print("ui: " + result["ui"]) except: NameError try: print("uri: " + result["uri"]) except: NameError try: print("name: " + result["name"]) except: NameError try: print("Source Vocabulary: " + result["rootSource"]) except: NameError print("\n") ##Either our search returned nothing, or we're at the end if jsonData["results"][0]["ui"] == "NONE": break print("*********") ================================================ FILE: samples/python/walk-hierarchy.py ================================================ ################################################################################################################################################################## # usage of the script # usage: python walk-hierarchy.py -k APIKEY -v VERSION -s SOURCE -i IDENTIFIER -o operation # note that computing descendants can take time, especially for terminology concepts with many descendants, closer to the tree-top of a given source vocabulary. ################################################################################################################################################################## from __future__ import print_function from Authentication import * import requests import json import argparse parser = argparse.ArgumentParser(description='process user given parameters') #parser.add_argument("-u", "--username", required = True, dest="username", help = "enter username") #parser.add_argument("-p", "--password", required = True, dest="password", help = "enter passowrd") parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") parser.add_argument("-s", "--source", required = True, dest="source", help = "enter a source vocabulary, like 'SNOMEDCT_US'") parser.add_argument("-i", "--identifier", required = True, dest="identifier", help = "enter an identifier, like 9468002") parser.add_argument("-o", "--operation", required = True, dest="operation", help = "choose an operation such as 'children', 'parents', 'descendants', or 'ancestors'") args = parser.parse_args() #username = args.username #password = args.password apikey = args.apikey version = args.version source = args.source identifier = args.identifier operation = args.operation uri = "https://uts-ws.nlm.nih.gov" content_endpoint = "/rest/content/"+version+"/source/"+source+"/"+identifier+"/"+operation ##get at ticket granting ticket for the session AuthClient = Authentication(apikey) tgt = AuthClient.gettgt() pageNumber=1 while True: query = {'ticket':AuthClient.getst(tgt),'pageNumber':pageNumber} r = requests.get(uri+content_endpoint,params=query) print(r.url) r.encoding = 'utf-8' items = json.loads(r.text) pageCount=items["pageCount"] print("Results for page " + str(pageNumber)+"\n") for result in items["result"]: try: print("ui: " + result["ui"]) except: NameError try: print("uri: " + result["uri"]) except: NameError try: print("name: " + result["name"]) except: NameError try: print("Source Vocabulary: " + result["rootSource"]) except: NameError print("\n") pageNumber += 1 if pageNumber > pageCount: print("End of result set") break print("*********")