# 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.

{% hint style="info" %}
You can find out all the valid Pydantic data types at <https://docs.pydantic.dev/latest/concepts/types/>
{% endhint %}

## 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`              | <ul><li>A standard "Universally Unique Identifier", common as an ID in many databases and systems.</li><li>In requests and responses will be represented as a <code>str</code>.</li></ul>                                                                                                                                                      |
| `datetime.datetime` | <ul><li>A Python datetime.datetime.</li><li>In requests and responses will be represented as a <code>str</code> in ISO 8601 format, like: <code>2024-03-20T09:41:00+07:00</code>.</li></ul>                                                                                                                                                    |
| `frozenset`         | <ul><li>In requests, a list will be read, eliminating duplicates and converting it to a <code>set</code>.</li><li>In responses, the <code>set</code> will be converted to a <code>list</code>.</li><li>The generated schema will specify that the <code>set</code> values are unique (using JSON Schema's <code>uniqueItems</code>).</li></ul> |

## Example program

Let's consider the following program:

{% code overflow="wrap" lineNumbers="true" %}

```python
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}
```

{% endcode %}

{% hint style="info" %}
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>
{% endhint %}

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

<figure><img src="https://4188609209-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhp4eambztJcKKLa7ysKG%2Fuploads%2Fg0USN8rO3Fp8F7BKnvzU%2FScreenshot%202024-03-20%20at%2010.48.34%20PM.png?alt=media&#x26;token=fb6784cb-88b3-4b0d-abad-7c5d4910afab" alt=""><figcaption><p>Fig. 1. Interact with the API endpoint in Postman</p></figcaption></figure>

{% hint style="info" %}

* The `generate_uuid()` function can be used to generate a dummy UUID.
* The value `P3D` in `process_after` is followed the ISO 8601 format. You can find out more details at <https://en.wikipedia.org/wiki/ISO_8601#Durations>
  {% endhint %}
