The Body¶
Warning
The current page still doesn't have a translation for this language.
But you can help translating it: Contributing.
Sometimes you might want to pass extra information into your handler and possibly customize the OpenAPI documentation for the request body schema or how to control its validation.
The simplest way is by importing the Body
object from Esmerald.
from pydantic import BaseModel, EmailStr
from esmerald import Body, Esmerald, Gateway, post
class User(BaseModel):
name: str
email: EmailStr
@post("/create")
async def create_user(
data: User = Body(title="Create User", description="Creates a new user in the system")
) -> None:
"""
Creates a user in the system and does not return anything.
Default status_code: 201
"""
app = Esmerald(routes=[Gateway(handler=create_user)])
URL Enconded¶
What if a payload needs to be sent with a specific format? For instance a form?
As explained here, the handler is expecting a data
field declared and from there
you can pass more details about the body.
from pydantic import BaseModel, EmailStr
from esmerald import Body, Esmerald, Gateway, post
from esmerald.enums import EncodingType
class User(BaseModel):
name: str
email: EmailStr
@post("/create")
async def create_user(
data: User = Body(
title="Create User",
description="Creates a new user in the system",
media_type=EncodingType.URL_ENCODED,
)
) -> None:
"""
Creates a user in the system and does not return anything.
Default status_code: 201
"""
app = Esmerald(routes=[Gateway(handler=create_user)])
There are different media_types
that can be used.
JSON
- application/json which happens to also be the default.URL_ENCODED
- application/x-www-form-urlencodedMULTI_PART
- multipart/form-data
All of those are standards in most of the frameworks out there.
Another example:
from pydantic import BaseModel, EmailStr
from esmerald import Body, Esmerald, Gateway, post
from esmerald.enums import EncodingType
class User(BaseModel):
name: str
email: EmailStr
@post("/create")
async def create_user(
data: User = Body(
title="Create User",
description="Creates a new user in the system",
media_type=EncodingType.MULTI_PART,
)
) -> None:
"""
Creates a user in the system and does not return anything.
Default status_code: 201
"""
app = Esmerald(routes=[Gateway(handler=create_user)])
Important¶
Since Body
is Pydantic field (sort of), that also means you can specify for instance,
the other parameters to be evaluated.
You can check the list of available parameters default as well.