Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
Problema con la solicitud de parche FastAPI desde Javascript

Hice un servicio REST en python usando FastAPI y necesito llamar a la API usando Javascript.

Este es mi servidor FastAPI:

 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

Y en mi script JS probé esta solicitud usando 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); } }

Pero cada vez que ejecuto esta solicitud, devuelve el error 422 Unprocessable Entity no procesable. ¿Tienes algún consejo para solucionar este problema?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Se generará el código de error 422 si la carga útil de la solicitud no coincide con la carga útil real aceptada por su API.

El modelo de Pydantic que usa, valida y acepta solo la carga de solicitud que coincide.

Ejemplo de carga útil que se puede utilizar aquí:

1)

 { "item_id":1, #integer "field_name": "some_name", #string "field_value": "some_value" #string }
  1. Cualquiera de los valores puede ser "nulo". Porque ha mencionado todos los campos como opcionales:
 { "item_id":null, #integer "field_name": "some_name", #string "field_value": null #string }
over 4 years ago · Santiago Trujillo Report

0

Como se señaló anteriormente, el error 422 Entidad no procesable se genera cuando la carga útil que se recibe no coincide con la esperada. Su secuencia de comandos envía un objeto JS, pero, en su lugar, debe enviar una cadena JSON, como se muestra en el código a continuación. Además, asegúrese de usar la URL correcta en su solicitud (ya que noté que la que está usando no coincide con ningún punto final en su API). Recuerde cambiar el atributo del cuerpo a body: json_data también.

 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); } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!