[Python] FastAPI returns "Error 422: Unprocessable entity" when I send multipart form data...

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have some issue with using Fetch API JavaScript method when sending some simple formData like so:

    function register() {
    var formData = new FormData();
    var textInputName = document.getElementById('textInputName');
    var sexButtonActive = document.querySelector('#buttonsMW > .btn.active');
    var imagesInput = document.getElementById('imagesInput');

    formData.append('name', textInputName.value);
    if (sexButtonActive != null){
    formData.append('sex', sexButtonActive.html())
    } else {
    formData.append('sex', "");
    }
    formData.append('images', imagesInput.files[0]);

    fetch('/user/register', {
    method: 'POST',
    data: formData,
    })
    .then(response => response.json());
    }
    document.querySelector("form").addEventListener("submit", register);


    And on the server side (FastAPI):

    @app.post("/user/register", status_code=201)
    def register_user(name: str = Form(...), sex: str = Form(...), images: List[UploadFile] = Form(...)):
    try:
    print(name)
    print(sex)
    print(images)
    return "OK"
    except Exception as err:
    print(err)
    print(traceback.format_exc())
    return "Error"


    After clicking on the submit button I get Error 422: Unprocessable entity. So, if I'm trying to add header Content-Type: multipart/form-data, it also doesn't help cause I get another Error 400: Bad Request. I want to understand what I am doing wrong, and how to process formData without such errors?

    Continue reading...

Compartilhe esta Página