I cannot seem to send a POST request to a FastAPI app through Postman.
from fastapi import FastAPI
from fastapi.params import Body
from pydantic import BaseModel
app = FastAPI()
class Post(BaseModel):
title : str
content : str
@app.get("/")
async def root():
return {"message": "Hello."}
@app.post("/createposts/")
def create_posts(new_post:Post):
print(new_post.title)
return {"new_post":f"title:"[new_post.title]}
I got the following error
INFO: Finished server process [44982]
INFO: Started server process [45121]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:64722 - "POST /createposts/ HTTP/1.1" 422 Unprocessable Entity
I'm following a tutorial and I cannot seem to find answers from other users.
I tried using the dict: Body(...)
input argument instead.
I am also using Postman and this is the error:
{
"detail": [
{
"loc": [
"body"
],
"msg": "value is not a valid dict",
"type": "type_error.dict"
}
]
}
Here's a screenshot of my request on Postman.
I made a POST request to the URL with the POST endpoint:
{
"title":"a",
"content":"b"
}
In Postman, you need to set the Body to be of type JSON.
In your screenshot, you have it set to Text:
It should be set to JSON:
And it should work as expectedNote 1, as shown in the screenshot.
As MatsLindh said in the comments, you can open the panel for the Code Snippet section to check how exactly Postman converts your request:
It should show
--header 'Content-Type: application/json'
for JSON. You probably have it as
--header 'Content-Type: text/plain'
for text, which FastAPI cannot parse properly.
Note 1
It's unrelated to the validation error, but you have a typo in the f-string on your endpoint. The closing double-quote on the value is misplaced.
This:
return {"new_post":f"title:"[new_post.title]}
should be:
return {"new_post": f"title:[{new_post.title}]"}