0

On getting the 422 Unprocessable Entity error.

Similar error : Python: FastAPI error 422 with POST request when sending JSON data

POST request code in Prescribe.js.

let res = await axios.post('http://127.0.0.1:8000/data', json).then(res => (console.log(res)))
            console.log(res + "hello");
            console.log(res.data);
            let result1 = res.data;
            console.log(JSON.stringify(eval("(" + result1 + ")")));
            result1 = JSON.stringify(eval("(" + result1 + ")"));
            var obj = JSON.parse(result1);
            console.log(typeof (obj.item));
            Object.entries(obj.item).forEach(([key, value]) => {
                console.log('response:', value);
            });

Python code in main.py.

from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from fastapi import FastAPI, Query, Path,Request, Form
from ner_model import check_name_entity_recognition, POS,check_name_entity_recognition_pdf
import requests
url = 'http://127.0.0.1:8000'
import json 
from app import *

app = FastAPI()

origins = [
    "http://localhost:3000",
]


app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)   



class Payload(BaseModel):
    data: str = ""


@app.post('/pdf')
async def createPdf(payload: Payload = None):

    print(payload.data)
    pred = await check_name_entity_recognition_pdf(payload.data)
    print(pred)
    # data= {"item" : out }
    # data=json.dumps(data)
    # data = data.encode("utf-8")
  
    # return data;
      
    sent=payload.data
    wordsList=sent.split()
    predsList = [j for sub in pred for j in sub]
    print(predsList )
    words=[]
    preds=[]

    for i in range(len(predsList)):
        if(predsList[i]!="O"):
            preds.append(predsList[i])
            words.append(wordsList[i])      
    start=0
    inputs=[]
    predictions=[]
    for current in range(len(words)):
        if(preds[current][0]=="B"):
            predictions.append(preds[current])
            inputs.append(" ".join(words[start:current]))
            start=current

    inputs.append(" ".join(words[start:]))
    inputs=inputs[1:]
    tempCounts={"B-DRUG":0,"B-STR":0,"B-FOR":0,"B-ROU":0,"B-DOS":0,"B-FRE":0,"B-DUR":0}
    for i in predictions:
        tempCounts[i]+=1
        totalDrug=max(tempCounts.values())
    data=[]
    for i in range(totalDrug):
        data.append({"B-DRUG":"NA","B-STR":"NA","B-FOR":"NA","B-ROU":"NA","B-DOS":"NA","B-FRE":"NA","B-DUR":"NA"})
    counts={"B-DRUG":0,"B-STR":0,"B-FOR":0,"B-ROU":0,"B-DOS":0,"B-FRE":0,"B-DUR":0}
    for i in range(len(predictions)):
        temp=counts[predictions[i]]
        data[temp][predictions[i]]=inputs[i]
        counts[predictions[i]]+=1
    # data= {"item" : data}
    # data=json.dumps(data)
    # data = data.encode("utf-8")
    return data


@app.post('/data')
async def main(payload: Payload = None):
    print(payload)
    out = await check_name_entity_recognition(payload.data)
    data= {"item" : out }
    data=json.dumps(data)
    data = data.encode("utf-8")
    print("->  ", payload)
    return data

Error in devtools

Headers, API test

JSON result

I tried console.log(response) and it is not showing the response.

sneha k
  • 11
  • 1
  • You haven't included what the definition of `payload` is - generally, 422 means that the content you submitted doesn't match what FastAPI expected for that endpoint (i.e. what you submitted doesn't match the definition of `Payload`). The body of the response returned by FastAPI will tell you more specifically which fields were missing or invalid and what the reason for the error was. – MatsLindh Mar 17 '23 at 10:30
  • @MatsLindh I have included now. – sneha k Mar 17 '23 at 10:35
  • The JSON result you've included is not the same result as you're trying to debug. You'll also want to look at what _you're actually submitting to the endpoint_ in your browser's development tools, not just what Javascript logs. – MatsLindh Mar 17 '23 at 10:44
  • Does this answer your question? [FastAPI and Axios POST request misconfiguration](https://stackoverflow.com/questions/70794813/fastapi-and-axios-post-request-misconfiguration) – Chris Mar 17 '23 at 12:08
  • Please have a look at related answers [here](https://stackoverflow.com/a/73096718/17865804), as well as [here](https://stackoverflow.com/a/70636163/17865804) and [here](https://stackoverflow.com/a/71741617/17865804) – Chris Mar 17 '23 at 12:09

0 Answers0