What’s the best way to handle chat messages with optional file uploads?

0
5
Asked By MellowPine47 On

I'm building a plain vanilla HTML, JavaScript, and CSS chat widget for a Shopify site. Users should be able to send a text message, attach a file with a message, or send a file without any text. The widget will call a FastAPI endpoint that accepts files through UploadFile.

I'm considering three approaches: always sending text and optional files together as multipart/form-data; switching between multipart/form-data and application/json depending on whether a file is attached; or sending the message and file as separate requests. Which approach would be the most reliable and maintainable?

3 Answers

Answered By SilverKite31 On

Switching between JSON and multipart usually creates unnecessary complexity. Once a FastAPI route includes Form or File parameters, its body is expected to be form data, so supporting JSON as an alternate format may require another route or custom request handling. Also, depending on your CORS and authentication headers, JSON requests may trigger a preflight request, so using multipart consistently may not even be slower.

Answered By QuietMaple6 On

The simplest FastAPI shape would be something like `message: str = Form("")` and `file: UploadFile | None = File(None)`. Install `python-multipart`, since FastAPI needs it to parse form uploads. Also, don’t manually set the Content-Type header when using fetch with FormData—the browser adds the required multipart boundary automatically. If you hardcode `multipart/form-data` without that boundary, parsing can fail.

Answered By CopperLynx82 On

I’d use one multipart/form-data request for every chat submission. FastAPI can accept the text as a Form field and the file as an optional UploadFile, so a text-only message is still handled by the same endpoint. The extra multipart headers add almost no meaningful overhead, while separate requests can get out of sync or partially fail. You don’t need an actual form element either—just create a FormData object in JavaScript and append the message and file when present.

MellowPine47 -

That makes sense. Keeping the message and attachment in one request should avoid having to synchronize two separate events.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.