Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

723
Visualizações
Curl works to POST data to FastAPI but React throws 422

I am writing a simple React application that takes form data and submits it to a Python API. The API is written in FastAPI and looks like this:

from fastapi import FastAPI
from pydantic import BaseModel
import json

app = FastAPI()


class TextInfer(BaseModel):
    text: str


@app.get("/")
def hello():
    return "hello"


@app.post("/predict")
def predict(req: TextInfer):
    return req

cURL works to send a simple JSON object to the predict endpoint:

> curl  -d '{"text": "sample text"}' -H  "Accept: application/json"  -H "Content-Type: application/json" -X POST http://0.0.0.0/predict
> {"text":"sample text"}%

But the React fetch call always results in a 422:

fetch('http://0.0.0.0/predict', {
      method: 'POST', 
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({'text': this.state.text})
    })
    .then(res => res.json())
    .then(
        (result) => {
          this.setState({
            isLoaded: true,
            predictions: result
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error: error
          });
        }
      )

this.state.text is a simple string; I've checked the browser console to verify that

{'text': this.state.text}

is a valid JSON object. It appears to be, e.g. {"text": "blah"}.

The response always reads as:

[HTTP/1.1 422 Unprocessable Entity 13ms]
Object { msg: "value is not a valid dict", type: "type_error.dict", loc: […] }
loc [ "body" ]

I am guessing this has something to do with how I implemented the Pydantic model, or how I am calling fetch from React, or both. Looking at similar questions has not helped resolve the issue. I also tried hard coding the body of the fetch call (in case my use of JSON.stringify was incorrect), but I get the same error.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

in

@app.post("/predict")
def predict(req: TextInfer):
    return req

you send back string, because you change json to string on line body: JSON.stringify({'text': this.state.text})

can you check what value is there? if it is truly string then you can just parse that string.

In python you can use just import json library like import json and then change last line from return req to return json.loads(req)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda