Loader Files
Here is the didactic documentation of the FilesPayloadBuilder class, structured to make it easier for developers and integrators to understand.
On this page
#1. Overview
The FilesPayloadBuilder class acts as a security filter and data transformer at the input layer of your API. When a user sends files through FastAPI, they arrive as UploadFile objects.
This class ensures that those files do not "break" the server by being too large or by having malicious or unsupported formats. After validation, it turns the raw data into a Python dictionary (payload) that is easy to handle by other parts of the system, such as image processing services or databases.
#2. Execution Flow
The processing flow of a file follows this logical path:
- Receiving: The API receives a list of files via form (Multipart).
- Asynchronous Reading: The file content is read from memory or temporary disk in a non-blocking way (
await f.read()). - Type Check: The system checks whether the
content_type(e.g. image/png) is in the list of allowed types. - Weight Check: The total size of the bytes read is compared with the configured limit (e.g. 10MB).
- Structuring: If everything is correct, the data is organized into a dictionary. If something fails, an HTTP exception is raised immediately, interrupting the process to protect the server.
#3. Methods Summary
| Method | Type | Short Description |
|---|---|---|
__init__ | Constructor | Sets up the business rules (maximum size and accepted types). |
build_images_payload | Coroutine (async) | Validates the list of files and generates the final data structure. |
#4. Architecture and Insights
- Reactive Security: By validating the size and MIME type right at the entrance, you avoid "Denial of Service" (DoS) attacks through the upload of giant files.
- Using a Set for Performance: The
allowed_typesvariable is converted to aset. In Python, checking whether an item exists in asetis much faster than in alistortuple, especially if the list of formats grows. - FastAPI Integration: Using
HTTPExceptionallows validation errors to be returned directly to the end user with appropriate status codes (400 Bad Request), without the need for extra try/except blocks in the API route.
#5. Class Details
#FilesPayloadBuilder Class
Description
Responsible for validating the integrity of files sent via upload and preparing them for internal processing. It centralizes the rules of "what can come in" to the system in terms of media files.
Arguments
max_mb(int): The maximum size allowed for each individual file in Megabytes.allowed_types(Iterable[str]): A collection of strings representing the accepted MIME types (e.g.["image/jpeg", "application/pdf"]).
#Methods
#1. build_images_payload
Description
This is the heart of the class. It goes through each uploaded file, reads its binary content and checks whether it meets the security requirements defined in the constructor.
Arguments
files(List[UploadFile]): A list of file objects coming from a FastAPI endpoint.
Returns
list[dict]: A list of dictionaries, where each dictionary contains:filename: Original name of the file.content_type: Format of the file.size_bytes: Real size in bytes.bytes: The raw binary content.
Raises
HTTPException (400): Raised if the file format is not allowed.HTTPException (400): Raised if the file exceeds the configured Megabyte limit.
Examples
builder = FilesPayloadBuilder(max_mb=2, allowed_types=["image/png"])
# Em uma rota FastAPI
@app.post("/upload")
async def upload_image(files: List[UploadFile]):
payload = await builder.build_images_payload(files)
return {"status": "sucesso", "arquivos_processados": len(payload)}Source: src/utils/loader_files.py