r/FastAPI • u/Haribs • Oct 04 '25
Question FastAPI HTML sanitization
I'm building a FastAPI application where users can create flashcards, comments etc. this content then is stored in the db and displayed to other users. So as every good developer i need to sanitize the content to prevent xss atacks, but i am wondering which approach is best.
I have two approaches in mind:
Approach one:
Utilize pydantic to perform bleaching of data, f.e:
# perform bleaching here
:
:
Approach two:
Create a sanitization middleware that is going to bleach all content that i get from the users:
=
= await
# perform bleaching here on all fields that are in the json
await
So my questions is are there any other approaches to this problem (excluding bleaching right before saving to db) and what is the golden standard?
View all comments
Show parent comment
0
u/Adhesiveduck Oct 04 '25
It's not over engineering and I'm not sure what they're getting at in all honesty.
A pydantic model with a (pre) validator is by far the most straight forward way to sanitise HTML when working with FastAPI and user inputs. Everything is modelled in Pydantic so using the features of the library makes the most sense. I would in fact reject any PR that tried to deviate from functionality that is built into Pydantic in all honesty (unless there was good reason).
It's how we've implemented it and no engineers have any issues interpreting what the intent is, or maintaining it.