Fix XSS in API Responses in Pyramid
XSS in API responses occurs when a Pyramid view reflects unsanitized user input in a response body without an explicit 'application/json' Content-Type. If the browser's MIME-sniffing logic identifies the payload as HTML, it will execute embedded scripts. In Pyramid, this usually happens when developers return a raw Response object or a string instead of using the built-in JSON renderer.
The Vulnerable Pattern
from pyramid.view import view_config from pyramid.response import Response
@view_config(route_name=‘profile_api’) def profile_api(request): user_name = request.params.get(‘name’, ‘Anonymous’) # VULNERABLE: Returns a string with default ‘text/html’ content type. # Payload: ?name= return Response(f’{“status”: “ok”, “user”: “{user_name}”}’)
The Secure Implementation
To neutralize XSS in Pyramid APIs, leverage the 'renderer="json"' argument in the view configuration. This enforces the 'application/json' header, which instructs modern browsers to treat the response as data rather than executable markup. Additionally, always return a dictionary/list to be serialized by the framework rather than manually interpolating strings into a raw Response body. For legacy views where you must use the Response object, explicitly set 'content_type="application/json"' and use 'json.dumps()' to ensure proper encoding of special characters.
from pyramid.view import view_config
@view_config(route_name=‘profile_api’, renderer=‘json’) def profile_api(request): user_name = request.params.get(‘name’, ‘Anonymous’) # SECURE: Using the ‘json’ renderer ensures Content-Type is ‘application/json’. # The framework handles proper serialization and escaping. return { ‘status’: ‘ok’, ‘user’: user_name }
Your API Responses API
might be exposed to XSS
74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.