Skip to content

Instantly share code, notes, and snippets.

@sdhutchins
Created December 10, 2025 19:01
Show Gist options
  • Select an option

  • Save sdhutchins/60d719928884376f67eae51196edb3c9 to your computer and use it in GitHub Desktop.

Select an option

Save sdhutchins/60d719928884376f67eae51196edb3c9 to your computer and use it in GitHub Desktop.
Fetch the ProtVar API & Return JSON
"""
Fetch ProtVar API JSON response for a variant.
Edit HGVS or RS_ID below and set USE_HGVS or USE_RSID to True.
ProtVar API docs:
- https://www.ebi.ac.uk/ProtVar/api/swagger-ui/index.html
- https://www.ebi.ac.uk/ProtVar/api/docs
"""
import json
import re
import urllib.request
import urllib.parse
from pathlib import Path
# Configuration
HGVS = "NM_001204.7:c.354T>G p.(Cys118Trp)" # BMPR2 Pathogenic Variant
RS_ID = "rs137852743"
# Try HGVS or RSID
# Protvar only will return missense variants
USE_HGVS = True
USE_RSID = False
OUTPUT_FILE = "protvar_response.json"
def fetch_protvar_by_hgvs(hgvs: str) -> dict:
"""Query ProtVar mappings endpoint using HGVS notation."""
cdna_match = re.search(r'(N[MP]_\d+(?:\.\d+)?:c\.\d+[A-Z][>][A-Z])', hgvs)
cdna_variant = cdna_match.group(1) if cdna_match else hgvs
url = "https://www.ebi.ac.uk/ProtVar/api/mappings"
params = urllib.parse.urlencode({
"function": "true",
"structure": "true",
"population": "true",
"assembly": "AUTO"
})
data = json.dumps([cdna_variant]).encode('utf-8')
req = urllib.request.Request(
f"{url}?{params}",
data=data,
headers={'Content-Type': 'application/json'},
method='POST'
)
try:
with urllib.request.urlopen(req, timeout=20) as response:
return json.load(response)
except urllib.error.HTTPError as e:
print(f"Error: HTTP {e.code}")
return {}
except Exception as e:
print(f"Error: {e}")
return {}
def fetch_protvar_by_rsid(rsid: str) -> dict:
"""Query ProtVar variant endpoint using RS ID."""
url = f"https://www.ebi.ac.uk/ProtVar/api/variant/{rsid}"
try:
with urllib.request.urlopen(url, timeout=15) as response:
return json.load(response)
except urllib.error.HTTPError as e:
print(f"Error: HTTP {e.code}")
return {}
except Exception as e:
print(f"Error: {e}")
return {}
if __name__ == "__main__":
if USE_HGVS:
print(f"Fetching ProtVar data for HGVS: {HGVS}")
data = fetch_protvar_by_hgvs(HGVS)
elif USE_RSID:
print(f"Fetching ProtVar data for RS ID: {RS_ID}")
data = fetch_protvar_by_rsid(RS_ID)
else:
print("Set USE_HGVS or USE_RSID to True")
data = {}
output_path = Path(OUTPUT_FILE)
with open(output_path, 'w') as f:
json.dump(data, f, indent=2, default=str)
print(f"Saved to: {output_path}")
print(f"Size: {output_path.stat().st_size / 1024:.2f} KB")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment