2

I have this fastAPI POST endpoint (the comments are what I tested according to what I found on the web):

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Any
from fastapi import Body

app = FastAPI()

class Data_schema(BaseModel):
    # jsonObj: str
    # data: Any
    somekey: str


@app.post("/")
async def get_item(payload: Data_schema):
# async def get_item(payload):
# async def get_item(payload: str = Body(..., embed=True)):
    return payload

And I test it with:

import requests
import json

data = {'somekey': 'somevalue'}

jsonObj = json.dumps(data, indent=4, default=str)
# jsonObj = json.dumps(data)

requests.post('http://127.0.0.1:8000/', data=data)
# requests.post('http://127.0.0.1:8000/', json=jsonObj)
# requests.post('http://127.0.0.1:8000/', json=data)
# requests.post('http://127.0.0.1:8000/', json=jsonObj)

I cannot get something else than 422 Unprocessable Entity. I am using python 3.10. Where do I do wrong ? Thank you

PierreL
  • 169
  • 9
  • You can try `return payload.dict()`. – Jedore Oct 18 '22 at 15:07
  • 1
    Please have a look [this answer](https://stackoverflow.com/a/70636163/17865804), as well as [this](https://stackoverflow.com/a/71741617/17865804) and [this](https://stackoverflow.com/a/73761724/17865804) on how to post JSON data to FastAPI backend. – Chris Oct 18 '22 at 15:17
  • Thank you, it works now with `requests.post('http://127.0.0.1:8000/', json=data)`. It's possible that it was still working but that I didn't see it among the other errors when building this small example. – PierreL Oct 19 '22 at 07:22
  • For those who wonder how to get the exact error message it's just `response = requests.post('http://127.0.0.1:8000/', json=data)` `print(response.content)` – PierreL Oct 19 '22 at 07:26

0 Answers0