ajaxfetchfastapijquery-ajax

Why does Switching from JQuery AJAX to Fetch cause a 422 Error?


I'm trying to convert a small FastAPI web app from JQuery AJAX to Fetch API.

The AJAX call sends some JSON to the server which is run through a function on the backend. The original JQuery code looks like this:

    static run_task_one(E1, E2, E3, n1, n2, success, error) {
        $.ajax({
            url: "/run/task/one",
            type: "POST",
            data: JSON.stringify({
                E1: E1,
                E2: E2,
                E3: E3,
                n1: n1,
                n2: n2,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: success,
            error: error,
        });
    }

This works fine.

My current implementation using FetchAPI is the following:

    static run_task_one(E1, E2, E3, n1, n2, success, error) {
        fetch("/run/task/one", {
            method: "POST",
            body: JSON.stringify({
                E1: E1,
                E2: E2,
                E3: E3,
                n1: n1,
                n2: n2,
            }),
            headers: {
              contentType: "application/json; charset=utf-8",
            },
        })
        .then((response) => response.json())

    }

This returns a 422 error code, along with the message: "value is not a valid dict" in the response. I've checked the response payload for each of the requests and both have the same value:

{"E1":"0.92","E2":"1.1","E3":"1.43","n1":"0.0025","n2":"0.0005"}

I understand FastAPI uses Pydantic, is it related to this package? Is the input provided by Fetch's body parameter different from JQuery's data parameter?


Solution

  • This error was caused by me incorrectly defining the Content-Type header in the fetch request. I used contentType as the request header, which was copied from the JQuery AJAX implementation.

    Using this header with Fetch created an extra header type called contentType, whilst Content-Type, the header I was trying to change, was set to a default value.

    enter image description here

    The default value is text/html; charset=UTF-8, which doesn't match the "application/json; charset=utf-8" value I'm trying to use. This meant my data was unreadable by FastAPI on the backend.