skip to content

In a FastAPI multipart upload endpoint, why does a plain Pydantic model parameter fail to read JSON metadata, and what works instead?

level: middleimportance: should knowfreq 25%

answer

  1. a request has one body
  2. the model becomes a form part
  3. a string where a dict was expected
  4. Pydantic's Json inside Form()

basics

~20 s

A multipart request has no separate JSON body, so FastAPI treats the model as one more form part, receives a string and answers 422. Send the metadata as a form field declared Annotated[Json[Model], Form()], parse it yourself, or use flat form fields.

solid answer

~40 s

A request has one body and one encoding; an upload makes it `multipart/form-data`, and the docs state that `File` and `Form` parameters cannot be combined with `Body` fields expected as JSON. If I declare `options: ImportOptions` next to `file: UploadFile`, FastAPI folds the model into the form schema, the part arrives as a string, and validation fails with a 422 of type `model_attributes_type`. What works is sending the metadata as a form field declared `Annotated[Json[ImportOptions], Form()]`: Pydantic's `Json` parses the string and validates it, and errors keep FastAPI's normal 422 shape. Alternatives are a `str` field parsed with `model_validate_json`, where I must turn `ValidationError` into a 4xx myself, or flat `Form()` fields.

code

python · 20 lines
python
from typing import Annotated

from fastapi import FastAPI, Form, UploadFile
from pydantic import BaseModel, Json

app = FastAPI()


class ImportOptions(BaseModel):
    source: str
    dry_run: bool = False
    tags: list[str] = []


@app.post("/imports/orders")
async def import_orders(
    options: Annotated[Json[ImportOptions], Form()],  # a JSON string in a form field
    file: UploadFile,
):
    return {"options": options, "filename": file.filename}

go deeper

for a junior

Recall that one request carries one body encoding, so an upload endpoint cannot also take a separate JSON body.

for a middle

Explain why a plain model beside an UploadFile fails with 422 and how Annotated[Json[Model], Form()] carries structured metadata instead.

for a senior

Show you can spot the failing signature in review, keep validation errors as 4xx, and remember the metadata field is still bound by the parser's limits.

for a principal

Choose between metadata inside the multipart body and a two-step upload API based on payload shape, client types and where files are stored.

A CSV import often needs more than the file: a source system, a dry-run switch, a list of tags. The natural instinct is to declare a Pydantic model next to the `UploadFile` and expect a JSON body beside the file. That does not work, and the reason is how FastAPI reads a request body. ## One request, one body encoding An HTTP request has a single body with a single `Content-Type`. A file upload has to be `multipart/form-data`, so the whole body is multipart, and there is no separate JSON body to read. The FastAPI docs say it directly: you can declare `File` and `Form` parameters together, but not `Body` fields that you expect as JSON, because the body is encoded as `multipart/form-data` instead of `application/json`. ## What FastAPI does with a plain model parameter Declare `options: ImportOptions` beside `file: UploadFile` and FastAPI does not reject the signature. Because the endpoint has form or file parameters, it treats **all** body parameters as parts of one form body: - the generated schema shows a single `multipart/form-data` body with an `options` property and a `file` property; - at request time the `options` part arrives as a plain string, and validation fails with a 422 of type `model_attributes_type`, `Input should be a valid dictionary or object to extract fields from`; - a client that sends `application/json` instead gets a 422 reporting both `options` and `file` as missing. So the signature looks reasonable, the docs page looks reasonable, and every real request fails. ## What works instead | Approach | How | Validation errors | |---|---|---| | `Json` form field | `options: Annotated[Json[ImportOptions], Form()]` | FastAPI's normal 422, with `loc` like `["body", "options", "source"]` | | String field parsed by hand | `options: Annotated[str, Form()]` then `ImportOptions.model_validate_json(options)` | a raised `ValidationError` becomes a 500 unless you convert it | | Flat form fields | `source`, `dry_run`, `tags` as `Form()` parameters, or one form model holding the file too | normal 422 per field | | Two requests | upload the file, then post JSON that refers to the stored upload | each endpoint keeps its natural encoding | The **`Json` route** is usually the best fit. Pydantic's `Json[...]` type accepts a JSON string, parses it and validates the result against the inner model, so the endpoint receives a real `ImportOptions` and malformed metadata produces the same 422 shape as any other input. The client sends the metadata as an ordinary form field, as in the `curl` example; a part content type of `application/json` on that field is accepted but not required, because FastAPI reads a non-file part as text. The **manual route** works but moves error handling into your code: catch `ValidationError` and raise `HTTPException(status_code=422, ...)`, or the client sees an internal server error. **Flat fields** suit a handful of simple options and keep the browser form usable. Nested lists and objects do not fit naturally into form fields, which is when the `Json` field wins. ## The client side The metadata has to be sent as a form field, and every common client can do that: - `curl` takes it as one more `-F` option, as in the example; - a browser script builds a `FormData` object, appends the file and the result of `JSON.stringify(options)` as a string field, and posts it without setting `Content-Type` by hand, so the boundary is filled in; - a Python HTTP client passes the JSON string in its form-data argument and the file in its files argument. Whatever the client, the metadata is plain text inside the multipart body, and the server is the one place that turns it into a model. ## Things to check in review 1. The endpoint declares no Pydantic model parameter without `Form()` next to a file; if it does, every request fails with 422. 2. Metadata parsed by hand converts its validation error into a 4xx. 3. Size and count limits apply to the metadata too: the field is a non-file part, so Starlette rejects it above 1 MB with a 400. 4. The docs or client SDK tell callers to send the metadata as a form field, not as a JSON body. The interview point is that the limitation is the HTTP body, not FastAPI, and that FastAPI gives you a clean way to carry structured data inside the multipart body when you need it.

  • In FastAPI, what happens when an upload endpoint parses JSON metadata with model_validate_json and the client sends invalid metadata?
    Pydantic raises `ValidationError` inside the endpoint, and FastAPI does not turn an error raised there into its 422 response, so the client gets a 500. Catch it and raise `HTTPException(status_code=422, detail=...)`, or declare the field as `Annotated[Json[Model], Form()]` so FastAPI validates it before the endpoint runs.
  • When is a two-request design better than JSON metadata inside a FastAPI multipart upload?
    When the metadata is large or nested, when the file is uploaded by a different component than the one that knows the options, or when uploads go straight to object storage. The client stores the file first, gets an identifier back, and then posts a normal JSON body that references it, so each endpoint keeps its natural encoding and validation.

  • A FastAPI endpoint can read a JSON body and an uploaded file in one request.
  • A model parameter beside an UploadFile is filled from a JSON part automatically.
  • A ValidationError raised inside the endpoint becomes FastAPI's 422 response.
  • This is a FastAPI limitation that a newer release will remove.