Search code examples
javascriptpythonrestfetchfastapi

Problem with FastAPI patch request from JavaScript


I made a REST service on python using FastAPI and I need to call the API using Javascript.

This is my FastAPI server:

class FieldUpdate(BaseModel):
item_id: Optional[int] = None
field_name: Optional[str] = None
field_value: Optional[str] = None

@router.patch("/update/item", response_model=FieldUpdate)
def update_item(body: FieldUpdate):
    item_id = body.item_id
    field_name = body.field_name
    field_value = body.field_value
    ctx_sle = get my current contenxt
    status = execute method after contenxt initialization (it has nothing to do with running the API)
    return status

And in my JS script I tried this request using fetch

class FieldUpdate {
  constructor(item_id, field_name, field_value) {
    this.item_id = item_id;
    this.field_name = field_name;
    this.field_value = field_value;
  }

}
async function update_field_from_cell(field) {


const url = "http://127.0.0.1:8080/scriptlab/update/item";
  try {
    await fetch(url, {
      method: "PATCH",
      headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
      body: field
    })
      .then(function(response) {
        console.log(response.status);
        console.log(response.text());
      });
  } catch (error) {
    console.log(error);
  }

}

But every time I run this request, it returns the 422 Unprocessable Entity error. Do you have any tips to solve this problem?


Solution

  • As pointed out earlier, as well as explained in this answer in detail, the 422 Unprocessable Entity error is thrown when the payload received does not match the expected one, or some required field(s) is missing. Your script sends a JS object, whereas it should instead send a JSON string, as shown in the code below. Also, please make sure to use the correct URL in your request (as it seems that the one you are currently using does not match any endpoint in your API). Please remember to change the body attribute to body: json_data as well as required.

    Example

    For more examples and details, see the linked answer above.

    async function update_field_from_cell(field) {
        var obj = {"item_id": field.item_id, "field_name": field.field_name, "field_value": field.field_value};
        json_data = JSON.stringify(obj);
        const url = "http://127.0.0.1:8000/update/item";
          try {
            await fetch(url, {
              method: "PATCH",
              headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
              body: json_data
            })
              .then(function(response) {
                console.log(response.status);
                console.log(response.text());
              });
          } catch (error) {
            console.log(error);
          }
    }