Receive JSON
data
You would normally use Pydantic models to declare a request body - if you were about to receive data in JSON
form - thus benefiting from the validation that Pydantic has to offer (for more options on how to post JSON
data, have a look at this answer). So, you would define a model like this:
from pydantic import BaseModel
class Item(BaseModel):
token: str
team_id: str
team_domain: str
# etc.
@app.post("/")
def root(item: Item):
print(item.dict()) # convert to dictionary (if required)
return item
The payload would look like this:
{
"token": "gIkuvaNzQIHg97ATvDxqgjtO"
"team_id": "Foo",
"team_domain": "bar",
# etc.
}
Receive Form
data
If, however, you were about to receive the payload as Form
data, just like what slack API does (as shown in the link you provided), you could use Form
fileds. With Form
fields, your payload will still be validated against those fields and the type you define them with. You would need, however, to define all the parameters in the endpoint, as described in the above link and as shown below:
from fastapi import Form
@app.post("/")
def root(token: str = Form(...), team_id: str = Form(...), team_domain: str = Form(...)):
return {"token": token, "team_id": team_id, "team_domain": team_domain}
or to avoid that, you may want to have a look at this post, which describes how to use Pydantic models with Form
fields. As suggested in one of the answers, you can do that even without using Pydantic models, but instead with creating a custom dependency class using the @dataclass
decorator, which allows you to define classes with less code. Example:
from dataclasses import dataclass
from fastapi import FastAPI, Form, Depends
@dataclass
class Item:
token: str = Form(...)
team_id: str = Form(...)
team_domain: str = Form(...)
#...
@app.post("/")
def root(data: Item = Depends()):
return data
As FastAPI is actually Starlette underneath, even if you still had to access the request body in the way you do in the question, you should rather use methods such as request.json()
or request.form()
, as described in Starlette documentation, which allow you to get the request body parsed as JSON
or form-data
, respectively.