Tipos de Datos Extra¶
Hasta ahora, has estado usando tipos de datos comunes, como:
int
float
str
bool
Pero también puedes usar tipos de datos más complejos.
Y seguirás teniendo las mismas funcionalidades como hasta ahora:
- Gran soporte de editor.
- Conversión de datos de requests entrantes.
- Conversión de datos para datos de response.
- Validación de datos.
- Anotación y documentación automática.
Otros tipos de datos¶
Aquí hay algunos de los tipos de datos adicionales que puedes usar:
UUID
:- Un "Identificador Universalmente Único" estándar, común como un ID en muchas bases de datos y sistemas.
- En requests y responses se representará como un
str
.
datetime.datetime
:- Un
datetime.datetime
de Python. - En requests y responses se representará como un
str
en formato ISO 8601, como:2008-09-15T15:53:00+05:00
.
- Un
datetime.date
:datetime.date
de Python.- En requests y responses se representará como un
str
en formato ISO 8601, como:2008-09-15
.
datetime.time
:- Un
datetime.time
de Python. - En requests y responses se representará como un
str
en formato ISO 8601, como:14:23:55.003
.
- Un
datetime.timedelta
:- Un
datetime.timedelta
de Python. - En requests y responses se representará como un
float
de segundos totales. - Pydantic también permite representarlo como una "codificación de diferencia horaria ISO 8601", consulta la documentación para más información.
- Un
frozenset
:- En requests y responses, tratado igual que un
set
:- En requests, se leerá una list, eliminando duplicados y convirtiéndola en un
set
. - En responses, el
set
se convertirá en unalist
. - El esquema generado especificará que los valores del
set
son únicos (usandouniqueItems
de JSON Schema).
- En requests, se leerá una list, eliminando duplicados y convirtiéndola en un
- En requests y responses, tratado igual que un
bytes
:bytes
estándar de Python.- En requests y responses se tratará como
str
. - El esquema generado especificará que es un
str
con "binary" como "format".
Decimal
:Decimal
estándar de Python.- En requests y responses, manejado igual que un
float
.
- Puedes revisar todos los tipos de datos válidos de Pydantic aquí: Tipos de datos de Pydantic.
Ejemplo¶
Aquí tienes un ejemplo de una path operation con parámetros usando algunos de los tipos anteriores.
from datetime import datetime, time, timedelta
from typing import Annotated
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime, Body()],
end_datetime: Annotated[datetime, Body()],
process_after: Annotated[timedelta, Body()],
repeat_at: Annotated[time | None, Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
🤓 Other versions and variants
from datetime import datetime, time, timedelta
from typing import Annotated, Union
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime, Body()],
end_datetime: Annotated[datetime, Body()],
process_after: Annotated[timedelta, Body()],
repeat_at: Annotated[Union[time, None], Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
from datetime import datetime, time, timedelta
from typing import Union
from uuid import UUID
from fastapi import Body, FastAPI
from typing_extensions import Annotated
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime, Body()],
end_datetime: Annotated[datetime, Body()],
process_after: Annotated[timedelta, Body()],
repeat_at: Annotated[Union[time, None], Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
Tip
Prefer to use the Annotated
version if possible.
from datetime import datetime, time, timedelta
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: datetime = Body(),
end_datetime: datetime = Body(),
process_after: timedelta = Body(),
repeat_at: time | None = Body(default=None),
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
Tip
Prefer to use the Annotated
version if possible.
from datetime import datetime, time, timedelta
from typing import Union
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: datetime = Body(),
end_datetime: datetime = Body(),
process_after: timedelta = Body(),
repeat_at: Union[time, None] = Body(default=None),
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
Nota que los parámetros dentro de la función tienen su tipo de dato natural, y puedes, por ejemplo, realizar manipulaciones de fechas normales, como:
from datetime import datetime, time, timedelta
from typing import Annotated
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime, Body()],
end_datetime: Annotated[datetime, Body()],
process_after: Annotated[timedelta, Body()],
repeat_at: Annotated[time | None, Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
🤓 Other versions and variants
from datetime import datetime, time, timedelta
from typing import Annotated, Union
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime, Body()],
end_datetime: Annotated[datetime, Body()],
process_after: Annotated[timedelta, Body()],
repeat_at: Annotated[Union[time, None], Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
from datetime import datetime, time, timedelta
from typing import Union
from uuid import UUID
from fastapi import Body, FastAPI
from typing_extensions import Annotated
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime, Body()],
end_datetime: Annotated[datetime, Body()],
process_after: Annotated[timedelta, Body()],
repeat_at: Annotated[Union[time, None], Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
Tip
Prefer to use the Annotated
version if possible.
from datetime import datetime, time, timedelta
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: datetime = Body(),
end_datetime: datetime = Body(),
process_after: timedelta = Body(),
repeat_at: time | None = Body(default=None),
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}
Tip
Prefer to use the Annotated
version if possible.
from datetime import datetime, time, timedelta
from typing import Union
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: datetime = Body(),
end_datetime: datetime = Body(),
process_after: timedelta = Body(),
repeat_at: Union[time, None] = Body(default=None),
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"process_after": process_after,
"repeat_at": repeat_at,
"start_process": start_process,
"duration": duration,
}