GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Flask

XSS in API responses occurs when an endpoint reflects untrusted input without enforcing a strict JSON Content-Type or performing proper output encoding. If a browser can be tricked into rendering the API response as 'text/html', any embedded scripts will execute in the context of the origin. In Flask, this usually happens when developers return raw strings or f-strings instead of using the built-in serialization utilities.

The Vulnerable Pattern

@app.route('/api/profile')
def profile():
    username = request.args.get('username')
    # VULNERABLE: Returns raw string, defaults to text/html. 
    # An attacker can pass ?username=
    return f"{{'user': '{username}', 'status': 'active'}}"

The Secure Implementation

The exploit relies on MIME-type sniffing. By returning a raw string, the browser may interpret the response as HTML. To kill this bug: 1. Always use `jsonify()` which automatically sets the 'Content-Type: application/json' header, preventing the browser from executing the body as markup. 2. For custom responses, explicitly set the 'X-Content-Type-Options: nosniff' header to prevent the browser from deviating from the declared MIME type. 3. Never manually concatenate JSON strings with user input.

from flask import jsonify

@app.route(‘/api/profile’) def profile(): username = request.args.get(‘username’) # SECURE: jsonify() sets Content-Type to application/json and escapes data return jsonify(user=username, status=‘active’)

System Alert • ID: 7783
Target: API Responses API
Potential Vulnerability

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.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.