1

The codes are as shown below.

Backend

api.py

@app.post("/caption")
async def caption(image: UploadFile = File(...)) -> str:
    # produce the caption
    caption = apiCaption(image)

    # save the image and caption information
    status = await apiSaveData(image, caption)

    return caption if status else "Something went wrong"

Frontend

submit.js
export default function SubmitButton({ image }) {
  const handleSubmission = async () => {
    let formData = new FormData();
    console.log(image);
    formData.append("file", image);

    await fetch("http://localhost:8000/caption", {
      method: "POST",
      body: formData,
    })
      .then(response => response.json())
      .then(result => {
        console.log("Caption:", result);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  };
  return (
    <div>
      <button disabled={!image} onClick={handleSubmission}>
        Submit
      </button>
    </div>
  );
}

The server keeps showing:

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) error

I really don't know why and the error code is quite ambiguous so cannot get the point.

1
  • Hi 👋, have you added the header to your api call? I mean headers: { "Content-type": "application/json" }, Because I saw a problem similar for 422 status maybe could help -> stackoverflow.com/questions/59929028/… Commented Sep 16, 2022 at 3:16

1 Answer 1

2

Make sure that on client side you use the same key (parameter's name) given on server side for UploadFile. In your case, that is image, as shown in this line of your code:

async def caption(image: UploadFile = File(...))
                  ^^^^^

Hence, on client side, when appending the file to the FormData instance, you should use that key instead:

formData.append("image", image);

Please have a look at this answer for more details and examples. Also, for future reference, the 422 status code is not quite ambiguous, as you stated. The 422 response body will contain an error message about which field(s) is missing or doesn’t match the expected format, which will help you to resolve the issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.