FastAPI - Getting Started with POST requests

by
Jeremy Canfield |
Updated: April 14 2025
| FastAPI articles
Let's say you want to POST JSON to one of your FastAPI endpoints and return some response. In this example, curl is used to post JSON to the FastAPI endpoint.
curl \
--request POST \
--url fastapi.example.com/api/v1 \
--header 'content-type: application/json' \
--data '{ "foo": "bar" }'
Here is the boilterplate code to handle the request and provide a response.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class variables(BaseModel):
foo: str
bar: str
@app.post("/api/vi")
async def api_v1(item: variables):
return item
In this example, FastAPI would simply return the JSON that was submitted in the POST request.
~]$ curl --request POST --url fastapi.example.com/api/v1 --header 'content-type: application/json' --data '{ "foo": "Hello", "bar": "World" }'
{"foo":"Hello","bar":"World"}
But what if we only post foo and not bar?
~]$ curl --request POST --url fastapi.example.com/api/v1 --header 'content-type: application/json' --data '{ "foo": "Hello" }' | jq
{
"detail": [
{
"type": "missing",
"loc": [
"body",
"bar"
],
"msg": "Field required",
"input": {
"foo": "Hello"
}
}
]
}
"missing" was returned and makes for a bit of messy output. You can give default values
- None for str (strings)
- True or False for bool (booleans)
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class variables(BaseModel):
foo: str = None
bar: str = None
validate: bool = False
@app.post("/api/vi")
async def api_v1(item: variables):
return item
Often, you are going to want to do something with the value of the JSON.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class variables(BaseModel):
queue_name: str
@app.post("/api/vi")
async def api_v1(item: variables):
return item.foo, item.bar
Did you find this article helpful?
If so, consider buying me a coffee over at