Page cover image

🍓Unit 13: Data Types

Introduction

Besides primitive data types (int, float, str, bool), user-defined data types, FastAPI also supports advanced data types such as UUID, datetime. In this unit, we will delve into the use of these data types within the context of FastAPI.

You can find out all the valid Pydantic data types at https://docs.pydantic.dev/latest/concepts/types/

Extra data types

In the following table, we present additional data types from Pydantic. Because these types are provided by Pydantic, they offer all the useful features, including editor support, data conversion for incoming requests and responses, data validation, and automatic annotation and documentation.

Data types
Description

UUID

  • A standard "Universally Unique Identifier", common as an ID in many databases and systems.

  • In requests and responses will be represented as a str.

datetime.datetime

  • A Python datetime.datetime.

  • In requests and responses will be represented as a str in ISO 8601 format, like: 2024-03-20T09:41:00+07:00.

frozenset

  • In requests, a list will be read, eliminating duplicates and converting it to a set.

  • In responses, the set will be converted to a list.

  • The generated schema will specify that the set values are unique (using JSON Schema's uniqueItems).

Example program

Let's consider the following program:

from datetime import datetime, time, timedelta
from typing import Annotated
from uuid import UUID, uuid4
from fastapi import FastAPI, Body

app = FastAPI()

@app.get("/generate-uuid/")
async def generate_uuid():
    """Generate a dummy UUID"""
    return str(uuid4())

@app.put("/items/{item_id}")
async def read_item(
        item_id: UUID,
        start_datetime: Annotated[datetime | None, Body()],
        end_datetime: Annotated[datetime | None, Body()],
        repeat_at: Annotated[time | None, Body()],
        process_after: Annotated[timedelta | None, Body()]
        ):
    """A demo API endpoint to create a new item with the given parameters"""
    start_process = start_datetime + process_after
    duration = end_datetime - start_process
    return {"item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, "repeat_at": repeat_at, "process_after": process_after, "start_process": start_process, "duration": duration}

In case you don't know how to interact with the program in Postman, you can interact with its API Docs available at http://127.0.0.1:8000/docs and http://127.0.0.1:8000/redoc

Fig. 1 shows how to interact with the program in Postman.

Fig. 1. Interact with the API endpoint in Postman

Last updated