10 ClinicalTrials.gov
Documentation of a systematic search.
import json
import re
import requests
from datetime import datetime
# Dictionary for search fields and their strings.
# Keys must be named as the query-string parameters of the API's "/studies" endpoint.
query = {} 10.1 Prepared search strategy
Structure of search strategy according to the ECLIPSE framework:
- Expectation: What is the need for curricula to improve spiritual care? (Not used in search)
- Client group: Patients receiving palliative care
- Location: Western world (Not used in search)
- Impact: Improved education
- Professionals: Nurses and physicians
- Service: Spiritual care
Filters used in search:
- Language: None
- Publication years: None
- Other filters: None
Advice on the search syntax of ClinicalTrials.gov is available in Table 2 of [1].
This is the prepared search strategy in expert search syntax of ClinicalTrials.gov. We will use this syntax to search via the new ClinicalTrials.gov API.
Note (see here):
Please note that the COVERAGE and EXPANSION operators are not fully implemented on the modernized ClinicalTrials.gov.
Expert query syntax
It is possible to filter with a query string in Essie expression syntax. This will allow for advanced searching. The query string will be sent in the filter.advanced parameter of the API.
Enter search string in between the triple quotes!
query['filter.advanced'] = """
(
AREA[BasicSearch](
palliative OR
"end-of-life" OR "eol care" OR
"terminal care" OR
"terminally ill" OR
hospice OR
"existential care"
)
AND
AREA[BasicSearch](
education OR
learning OR
teaching OR
coaching OR
school OR
curriculum OR
course OR
competence OR competency OR
expertise OR
education OR
training OR
instruction OR
self-assessment OR
"professional development" OR
skill OR skills
)
AND
AREA[BasicSearch](
"health care professional" OR "healthcare professional" OR
"health care provider" OR "healthcare provider" OR
"health care worker" OR "healthcare worker" OR
"health occupations" OR
personnel OR
staff OR
nurse OR nursing OR
practitioner OR
physician OR
caregiver OR
(student AND (health OR healthcare OR medical OR nursing)) OR
(team AND (health OR healthcare OR medical OR nursing))
)
AND
AREA[InterventionSearch](
(spiritual* OR religi* OR pastoral) AND (care OR support OR intervention* OR healing OR guidance OR therap* OR treatment* OR supervision OR needs OR councel*)
)
)
OR
(
AREA[BasicSearch](
"epicc spiritual care education standard" OR
"epicc spiritual care competency self-assessment tool"
)
)
"""Combination of concepts
The individual search components will be combined with the Boolean operator AND by specifying the respective query parameters for each search string in the API call.
10.2 Documentation of the search process
This documentation includes all elements required for reporting according to the PRISMA for Searching (PRISMA-S) guideline.
Host/platform (incl. version)
- U.S. National Library of Medicine
URL
Database(s) (incl. database codes and update status)
- ClinicalTrials.gov
Temporal coverage of database
Limits and restrictions (e.g., date or time period, language, study design)
- None
Published search filter(s)
- None
Prior work used in search strategy
- See MEDLINE search!
Search form and search field(s)
Search fields:
AREA[ConditionSearch](same as Conditons/disease in the search form orquery.condparameter of the API)AREA[BasicSearch](same as Other terms in the search form orquery.termparameter of the API)AREA[InterventionSearch](same as Intervention/treatment in the search form orquery.intrparameter of the API)AREA[OutcomeSearch](same as Outcome measure in the search form orquery.outcparameter of the API)
The search was carried out using the modernized API, see below.
Peer review of search strategy
- None
Date of the search
today = datetime.today().strftime("%Y-%m-%d")
print(today)2026-10-29
Search using the API
The search was done by querying the (as of 2024) modernized API.
API version
r = requests.get('https://clinicaltrials.gov/api/v2/version')
version_info = r.json()
print(version_info){'apiVersion': '2.0.5', 'dataTimestamp': '2026-10-29T09:00:05'}
# HTTP query parameters to be sent to the API
params = {}
# Prepare the search strings and add to HTTP query parameters:
# Remove surplus whitespace from the search strings.
# This allows for longer search strings as length of query URL might be limited.
# Strings with only whitespace will not be used in the API query.
for field, str in query.items():
search_string = re.sub('^\\s+$', '', re.sub('\\s+', ' ', str).strip())
if (search_string):
params[field] = search_string
# Number of records to fetch in a single batch; maximum allowed is 1000
page_size = 1000
params['pageSize'] = page_size.__str__()
# Total number of studies found should be returned with first result page:
params['countTotal'] = 'true' # Query the API and fetch first page with results.
headers = { 'accept': 'application/json' }
r = requests.get('https://clinicaltrials.gov/api/v2/studies', headers = headers, params = params)if ( r.status_code == 200 ):
print('API returned HTTP status 200: OK. All is well.')
elif ( r.status_code == 400 ):
print('API returned HTTP status 400: Bad request. You might want to check the search terms.')
else:
print('API returned an HTTP status code not defined in the query documentation:', r.status_code, 'Something went wrong!')API returned HTTP status 200: OK. All is well.
Write the result to a JSON file:
# JSON file with the search results
json_file = 'ClinicalTrials_result_' + today + '.json'
with open(json_file, 'wb') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
fd.close()
print(json_file)ClinicalTrials_result_2026-10-29.json
# Get the JSON from the response
json_response = r.json()Total number of records found (before deduplication)
The number of records found as reported in the JSON file:
total_count = json_response['totalCount']
print(total_count)91
# TODO: Add code to download more than a single page!
if (total_count > page_size):
print('WARNING ' * 12)
print('WARNING: The number of records found is larger than the chunk we fetched! Not all records were downloaded!!!')
print('WARNING: Increase page_size above (but only 1000 is allowed) or change python code to download all results!')
print('WARNING ' * 12)
else:
print("OK. We did not find more records than we requested for download.")OK. We did not find more records than we requested for download.
# From now on we will work with the contents of the file we just saved. Just to be sure.
# Open the JSON file
try:
with open(json_file, 'r') as file:
json_string = file.read()
except FileNotFoundError:
print('Error: File "' + json_file + '" not found')
# exit()
file.close()counter = 0
try:
# Load the JSON data
query_results = json.loads(json_string)
# Get the list of studies
studies = query_results.get("studies", [])
# Extract the data for each study
# Definition of the study data structure incl. meaning of the elements:
# https://www.clinicaltrials.gov/data-api/about-api/study-data-structure
# For naming in the JSON see here: https://www.clinicaltrials.gov/data-api/api
ris_entries = []
for study in studies:
# print("study index:", counter) # for debugging
# For some fields we assume that they are present, for others we check.
accession_number = study["protocolSection"]["identificationModule"]["nctId"]
url = "https://www.clinicaltrials.gov/study/" + accession_number
date_retrieved = datetime.today().strftime("%Y-%m-%d")
database = "ClinicalTrials.gov"
database_provider = "U.S. National Library of Medicine"
if (study["protocolSection"]["identificationModule"].get("officialTitle")):
title = study["protocolSection"]["identificationModule"].get("officialTitle")
elif (study["protocolSection"]["identificationModule"].get("briefTitle")):
title = study["protocolSection"]["identificationModule"].get("briefTitle")
else:
title = ""
title = title.replace('\n', '\\n')
year = study["protocolSection"]["statusModule"]["studyFirstPostDateStruct"]["date"][0:4]
if (study["protocolSection"]["descriptionModule"].get("detailedDescription")):
abstract = study["protocolSection"]["descriptionModule"].get("detailedDescription")
elif (study["protocolSection"]["descriptionModule"].get("briefSummary")):
abstract = study["protocolSection"]["descriptionModule"].get("briefSummary")
else:
abstract = ""
abstract = abstract.replace('\n', '\\n')
# Create RIS-formatted string for the record
ris_record = f'TY - WEB\n'
ris_record += f'TI - {title}\n'
ris_record += f'PY - {year}\n'
ris_record += f'UR - {url}\n'
ris_record += f'RD - {date_retrieved}\n'
ris_record += f'AN - {accession_number}\n'
ris_record += f'DB - {database}\n'
ris_record += f'DP - {database_provider}\n'
ris_record += f'AB - {abstract}\n'
ris_record += f'ER - \n'
ris_entries.append(ris_record)
counter += 1
except json.JSONDecodeError:
print("Error: Invalid JSON data")
print('Processed', counter, 'study records')Processed 91 study records
# Create RIS file
ris_str = '\n'.join(ris_entries)ris_file = 'ClinicalTrials_records_' + today + '.ris'
with open(ris_file, "w") as rfile:
rfile.write(ris_str)
rfile.close()Quality checks of search result
Count number or records in export file(s):
!grep --count "^ER - " ClinicalTrials_records_*.ris91
File with the accession numbers of the records retrieved
The accession numbers of the records retrieved were written to a file:
!grep "^AN - " "ClinicalTrials_records_$(date -I).ris" | sed -e 's/^AN - //' -e 's/\s+//g' > "ClinicalTrials_AN_$(date -I).txt"The number of accession numbers in the file:
!wc -l "ClinicalTrials_AN_$(date -I).txt"91 ClinicalTrials_AN_2026-10-29.txt
Search carried out by
- Helge Knüttel
File with the prepared search strategy
- The prepared search strategy is contained in this file, see above.
Name of search strategy saved on host
- Not applicable.
Link to search strategy
- Not applicable.
Search strategy saved to file
- Not applicable. It was not possible to download a search strategy from the host.