Skip to content

Regression since v0.44.1 - Error 422 if Form is declared before File #1964

@thomasleveil

Description

@thomasleveil

Here's a branch with my use case:

from starlette.testclient import TestClient

from fastapi import FastAPI, File, Form

app = FastAPI()


@app.post("/file_before_form")
def file_before_form(
    file: bytes = File(...), city: str = Form(...),
):
    return {"file_content": file, "city": city}


@app.post("/file_after_form")
def file_after_form(
    city: str = Form(...), file: bytes = File(...),
):
    return {"file_content": file, "city": city}


client = TestClient(app)


def test_file_before_form():
    response = client.post(
        "/file_before_form", data={"city": "Thimphou"}, files={"file": "<file content>"}
    )
    assert response.status_code == 200, response.text
    assert response.json() == {"file_content": "<file content>", "city": "Thimphou"}


def test_file_after_form():
    response = client.post(
        "/file_after_form", data={"city": "Thimphou"}, files={"file": "<file content>"}
    )
    assert response.status_code == 200, response.text  # <-------------- this fails since ab2b86f
    assert response.json() == {"file_content": "<file content>", "city": "Thimphou"}

Description

Upgrading FastApi from 0.42.0 to 0.61.0 on one of my project, I stumbled upon a regression in which FastApi will respond with HTTP Error 422 when ever posting a form-data request to an endpoint where a File is declared after a Form.

Searching the Internet, I found another user suffering from this issue : https://stackoverflow.com/questions/61376754/fastapi-files-must-be-loaded-before-form-in-function-parameters

I've created a branch with tests to showcase the issue : https://github.com/thomasleveil/fastapi/tree/file_and_form_together

Environment

  • OS: Linux
  • FastAPI Version 0.44.1 and later
  • Python version: 3.8.5

Additional context

I've bisected the repo and figured out the regression was introduced in commit ab2b86f

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions