Fix XSS in API Responses in FastAPI
XSS in APIs occurs when user-controlled data is reflected in responses without proper sanitization or incorrect Content-Type headers. In FastAPI, using HTMLResponse or failing to enforce strict JSON serialization allows attackers to inject malicious scripts that execute in the context of the victim's session. To kill this bug, you must enforce strict output encoding and correct MIME types.
The Vulnerable Pattern
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get(‘/profile’)
async def get_profile(username: str):
# VULNERABLE: Direct string interpolation into HTMLResponse
# Payload: /profile?username=
html_content = f’
User: {username}
’
return HTMLResponse(content=html_content)
The Secure Implementation
The vulnerability exists because HTMLResponse tells the browser to parse the body as HTML, allowing script tags to execute. The fix is three-fold: 1) Default to JSONResponse. By setting 'Content-Type: application/json', modern browsers treat the payload as data, not executable code. 2) If rendering HTML, use a templating engine like Jinja2 which performs context-aware auto-escaping (converting '<' to '<'). 3) Set a strict Content-Security-Policy (CSP) header to prevent inline scripts from running even if an injection occurs.
from fastapi import FastAPI from fastapi.responses import JSONResponse from pydantic import BaseModel import htmlapp = FastAPI()
@app.get(‘/profile’) async def get_profile(username: str): # SECURE: Use JSONResponse to force application/json Content-Type # Browsers will not execute scripts inside JSON objects return JSONResponse(content={‘username’: username})
IF HTML IS REQUIRED: Use Jinja2 templates for auto-escaping
from fastapi.templating import Jinja2Templates templates = Jinja2Templates(directory=‘templates’)
@app.get(‘/profile-safe’) async def get_profile_safe(username: str): # Jinja2 automatically escapes HTML entities by default return templates.TemplateResponse(‘profile.html’, {‘username’: username})
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.