add whitelist proxy request method for external api calls

This commit is contained in:
Casey Wittrock 2025-11-02 20:46:50 -06:00
parent 697add510f
commit 1f33262e90
2 changed files with 32 additions and 0 deletions

View File

32
custom_ui/api/proxy.py Normal file
View File

@ -0,0 +1,32 @@
import frappe
import requests
from urllib.parse import urlparse
allowed_hosts = ["api.zippopotam.us"] # Update this list with trusted domains as needed
@frappe.whitelist(allow_guest=True)
def proxy_request(url, method="GET", data=None, headers=None):
"""
Generic proxy for external API requests.
WARNING: Only allow requests to trusted domains.
"""
parsed_url = urlparse(url)
if parsed_url.hostname not in allowed_hosts:
frappe.throw(f"Rquests to {parsed_url.hostname} are not allowed.", frappe.PermissionError)
try:
resp = requests.request(
method=method.upper(),
url=url,
json=frappe.parse_json(data) if data else None,
headers=frappe.parse_json(headers) if headers else None,
timeout=10
)
resp.raise_for_status()
try:
return resp.json()
except ValueError:
return {"text": resp.text}
except requests.exceptions.RequestException as e:
frappe.log_error(message=str(e), title="Proxy Request Failed")
frappe.throw("Failed to fetch data from external API.")