- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Authentication, Authorization and Security
- API Security Best Practices
- Input Sanitization
On this page
Input Sanitization in FastAPI with Pydantic
Published on August 14, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Any data arriving from outside an application — a request body, a query parameter, a header — has to be treated as untrusted until it's checked, since nothing on the server side can assume a client sent well-formed, safe data. Pydantic is what performs that check in FastAPI, parsing every incoming payload against a defined schema and rejecting anything that doesn't match before a route handler ever runs. What Pydantic validation actually guarantees is more specific than it might first appear, though — it closes off type confusion and malformed payloads reliably, but it isn't a general-purpose defense against every kind of injection attack, and knowing exactly where its protection ends is what determines whether the rest of an application is actually safe.
What Input Validation Actually Protects Against​
When a request reaches a FastAPI endpoint, Pydantic parses the payload against the declared schema before the route's own code runs. A field typed as int rejects a string; a field typed as str rejects a nested object; a payload missing a required field or carrying an unexpected structure gets rejected outright with a structured 422 response. This closes off type confusion attacks specifically — cases where sending an unexpected type causes downstream code to behave in an unintended way — and it does so unconditionally, before any application logic has a chance to run on unvalidated data.
Where this stops mapping onto every security claim commonly made about it is SQL injection. A str field, even with strict length limits and a narrow regex pattern applied, can still hold a syntactically valid string that happens to be a SQL injection payload — Field(pattern="^[a-zA-Z0-9_' ]+$") would still accept something like admin' OR '1'='1, since every character in that string is individually permitted by the pattern. Pydantic validates the shape of the data — its type, its length, whether it matches a pattern — not what a database would do with that string once it reaches a query. SQL injection is prevented by how a query is constructed, not by how its input was validated; a validated string still needs to go through a parameterized query or an ORM's query-building layer rather than being concatenated directly into raw SQL.
Building Strict Field Constraints with Pydantic​
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
username: str = Field(min_length=3, max_length=20, pattern="^[a-zA-Z0-9_]+$")
email: EmailStr
password: str = Field(min_length=8)
Field(min_length=3, max_length=20, pattern="^[a-zA-Z0-9_]+$") restricts username to alphanumeric characters and underscores within a defined length range — a request with username containing spaces, symbols, or exceeding 20 characters fails validation immediately. EmailStr checks the value against standard email address syntax before it reaches anywhere else in the application. Field(min_length=8) on password enforces a minimum length at the validation layer, rather than leaving that check to be repeated somewhere deeper in the application logic. None of these constraints touch what eventually happens to username or email once they reach a database query — that's a separate concern, covered next.
Why SQL Injection Needs a Different Defense​
A validated string is still just a string once it reaches the database layer — what matters is how that string gets incorporated into a query:
# Vulnerable — string concatenation, regardless of how strictly "username" was validated
query = f"SELECT * FROM users WHERE username = '{username}'"
cursor.execute(query)
# Safe — the driver handles the value as data, never as part of the query structure
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
# Safe — an ORM's query builder parameterizes automatically
from sqlmodel import select
session.exec(select(User).where(User.username == username))
The difference isn't about which string was "cleaner" going in — a value that passed every Pydantic constraint can still break the first version if it happens to contain a single quote positioned to alter the query's structure. The second and third versions never let the value influence the query's structure at all, regardless of what characters it contains, because the database driver or the ORM keeps the query template and the supplied data separate at the protocol level. This is why "the input was validated" and "the query is safe from injection" are two independent claims — both need to be true, and neither one implies the other.
Context-Specific Output Escaping​
Cross-Site Scripting exploits a different point in the pipeline: stored or reflected user content rendered into an HTML context without being escaped for that context, letting a browser interpret submitted text as executable markup rather than displaying it as plain text. The detail that matters most here is that escaping is a property of where data is being placed, not something to apply uniformly the moment data comes in — the same string might need HTML escaping in one context and no escaping at all in another, depending entirely on what's rendering it.
HTML template rendering: autoescaping is already the default​
For a FastAPI application rendering HTML through Jinja2Templates, current Starlette versions enable autoescaping by default for .html, .htm, and .xml templates the moment Jinja2Templates(directory=...) is used:
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/profile/{username}")
def profile(request: Request, username: str):
return templates.TemplateResponse(
request, "profile.html", {"username": username}
)
If username contains <script>alert('xss')</script>, the template engine renders it as the literal, inert text <script>alert('xss')</script> on the page automatically — no manual escaping call needed anywhere in the route. Calling html.escape() on the value before passing it to the template in this setup doesn't add protection; it risks double-escaping the value instead, turning & into &amp; on a value that was already escaped once by the template engine.
JSON APIs: the responsibility shifts to the frontend​
Most FastAPI applications return JSON, not rendered HTML, and JSON responses have no HTML execution context to escape for in the first place — a JSON string containing <script> is just a string value inside a JSON payload, not markup a browser is about to parse. Whatever eventually renders that string into a webpage — React, Vue, or any modern frontend framework — is responsible for escaping it at that point, and every mainstream framework already does this automatically the moment data is rendered through its standard templating or DOM-binding mechanism, rather than through raw, unescaped HTML insertion. Escaping a value with html.escape() before storing it or before returning it as JSON doesn't help this case and actively corrupts the data for any consumer that expected the original text back unmodified.
When manual escaping is actually necessary​
Manual escaping earns its place in narrower situations: constructing an HTML string by hand outside of a template engine's automatic escaping — building an email body, generating a PDF's HTML source, or working with a templating setup where autoescaping was explicitly disabled.
import html
def build_html_snippet(comment_text: str) -> str:
return f"<p>{html.escape(comment_text)}</p>"
html.escape() converts <, >, &, and quote characters into their safe entity equivalents — <script> becomes <script> — so a browser displays the text literally rather than parsing it as markup. This belongs specifically at the point where a raw HTML string is being assembled by hand, not as a blanket step applied to every piece of user input regardless of where it's headed next.
Key Takeaways​
Pydantic validation is a genuine, unconditional defense against type confusion and malformed payloads, but it validates shape, not database safety — SQL injection prevention comes from parameterized queries and ORM query builders, which keep user-supplied values separate from query structure regardless of what characters those values contain. Output escaping is context-specific by nature: an HTML template rendered through Jinja2Templates already autoescapes by default in current Starlette versions, a JSON API has no HTML context to escape for at all and relies on the consuming frontend to escape safely at render time, and manual html.escape() calls belong specifically where raw HTML is being hand-assembled outside of an autoescaping template engine — not applied indiscriminately to every field the moment it arrives.
Practice: Building a Validated Comment Model​
from pydantic import BaseModel, Field
class CommentCreate(BaseModel):
text: str = Field(min_length=1, max_length=200)
min_length=1 rejects an empty comment outright, and max_length=200 caps the stored length before it ever reaches the database — both checked at the validation layer, before a route handler's own code runs. Sending {"text": ""} fails with a 422 citing the minimum length; sending a 250-character string fails the same way, citing the maximum. Sending {"text": "<script>alert('xss')</script>"} succeeds, since every character here is a valid part of a str field with no length or pattern restriction violated — and that's the expected, correct outcome at this layer specifically. Validation confirms the payload is a well-formed string within the allowed length; it was never meant to be the layer responsible for deciding whether that string is safe to render as HTML later; that responsibility belongs to whichever output context eventually displays it, exactly as covered above.
Frequently Asked Questions​
If Pydantic validates a string field, is it safe to use that value directly in a SQL query?
No. Pydantic validation confirms a value's type, length, and pattern — it says nothing about what a database would do with that value once it's part of a query. A string can pass every Pydantic constraint and still be a valid SQL injection payload if it's concatenated directly into a query string. Parameterized queries or an ORM's query builder are what keep a value from influencing a query's structure, regardless of validation.
Should I call html.escape() on user input before saving it to the database?
Generally no. Escaping is specific to the context a value is being rendered into, and a value stored pre-escaped in the database becomes a problem the moment it's needed somewhere that doesn't expect HTML entities — a JSON API response, a plain-text export, or a search index. Escaping belongs at the point of output into a specific context, not applied blanket at input time.
I'm calling html.escape() in my route and also using Jinja2Templates — is that necessary?
Likely not, and it can actually cause problems. Current Starlette versions enable autoescaping by default for .html templates the moment Jinja2Templates(directory=...) is used, so the template engine already escapes rendered values automatically. Calling html.escape() before passing a value to the template risks double-escaping it, turning an already-safe & into & visibly on the page.
My FastAPI app only returns JSON — do I still need to worry about XSS?
The responsibility shifts, but it doesn't disappear. A JSON response has no HTML execution context of its own, so there's nothing to escape at that layer. Whatever frontend eventually renders that JSON data into a webpage — React, Vue, or similar — is responsible for escaping it safely at render time, which every mainstream frontend framework does automatically through its standard rendering mechanism.
A regex pattern on my username field allows quotes and special characters needed for names. Does that reopen a SQL injection risk?
It doesn't, as long as the value reaches the database through a parameterized query or ORM rather than raw string concatenation. The pattern constraint is about what characters a legitimate username may contain, not about SQL safety — SQL safety is guaranteed by how the query is built, independent of what characters happen to be present in the validated value.
Why did my test payload with <script> tags pass validation instead of getting rejected?
This is expected, not a bug. A field typed as a plain str with no length or pattern restriction that excludes those characters has no reason to reject that string — it's a syntactically valid string. Validation's job is confirming the data is well-formed and within any declared constraints; deciding whether a string is safe to render as HTML is a separate concern, handled at the point where that string is actually output into an HTML context.
Is EmailStr enough validation to trust an email address is real and deliverable?
No — EmailStr checks that a value matches standard email address syntax, not that the address actually exists or can receive mail. Confirming an address is real and reachable requires a separate step, typically sending a verification email and requiring the user to confirm it.
If I disable Jinja2's autoescape for a specific template, do I need to add manual escaping back?
Yes — disabling autoescape removes the automatic protection Starlette now enables by default, and any user-controlled value rendered in that template needs to be escaped manually (with html.escape() or Jinja2's own |e filter) at each point it's inserted, or the template becomes vulnerable to XSS from that value.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Rate Limiting
Next
HTTP Headers
-
What Input Validation Actually Protects Against
-
Building Strict Field Constraints with Pydantic
-
Why SQL Injection Needs a Different Defense
-
Context-Specific Output Escaping
- HTML template rendering: autoescaping is already the default
- JSON APIs: the responsibility shifts to the frontend
- When manual escaping is actually necessary
-
Key Takeaways
-
Practice: Building a Validated Comment Model
-
Frequently Asked Questions
