GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Bottle

Reflected XSS in Bottle APIs occurs when untrusted input is echoed back into the response body without strict content-type enforcement or proper output encoding. If the 'Content-Type' is not explicitly set to 'application/json', browsers may sniff the content and execute embedded scripts if the payload looks like HTML.

The Vulnerable Pattern

from bottle import route, request

@route(‘/api/greet’) def greet(): # VULNERABLE: Returns raw string which defaults to text/html # Attack: /api/greet?name= name = request.query.get(‘name’) return f’{“status”: “success”, “message”: “Hello {name}”}’

The Secure Implementation

The fix involves two primary layers of defense. First, avoid manual string concatenation for JSON responses; returning a Python dictionary causes Bottle to automatically set the 'application/json' header, which instructs the browser not to parse the body as HTML. Second, always ensure the 'X-Content-Type-Options: nosniff' header is present globally to prevent MIME-sniffing attacks where a browser might ignore the JSON content-type and execute the payload anyway.

from bottle import route, request, response
import json

@route(‘/api/greet’) def greet(): name = request.query.get(‘name’) # SECURE: Return a dictionary; Bottle auto-serializes to JSON # and sets Content-Type to application/json return {“status”: “success”, “message”: f”Hello {name}”}

@route(‘/api/manual’) def manual(): name = request.query.get(‘name’) # ALTERNATIVE SECURE: Explicitly set Content-Type and encode response.content_type = ‘application/json’ return json.dumps({“user”: name})

System Alert • ID: 5875
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.