CS504070 - FastAPI Tutorials
  • 🧩CS504070 - FastAPI Tutorials
  • 🔎Unit 1: Python Type Hint
  • ⚙️Unit 2: Pydantic
  • 🔃Unit 3: Concurrency
  • 💾Unit 4: Install FastAPI
  • 🍉Unit 5: Hello World!
  • 🍌Unit 6: Path Parameters
  • 🍋Unit 7: Query Parameters
  • 🍊Unit 8: Request Body
  • 🍐Unit 9: Query Parameters and Validations
  • 🍎Unit 10: Path Parameters and Validations
  • 🍏Unit 11: Multiple Parameters
  • 🍇Unit 12: Request Body - List Fields and Nested Models
  • 🍓Unit 13: Data Types
  • 🍪Unit 14: Cookie Parameters
  • 🫐Unit 15: Header Parameters
  • 🍈Unit 16: Response Model - Return Type
  • 🍒Unit 17: Additional Models
  • 🥑Unit 18: Implementing JWT Authentication with FastAPI
  • ⚙️Appendix A
  • 🍭Appendix B
Powered by GitBook
On this page
  • Introduction
  • Extra data types
  • Example program

Unit 13: Data Types

PreviousUnit 12: Request Body - List Fields and Nested ModelsNextUnit 14: Cookie Parameters

Last updated 1 year ago

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

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}

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

  • The generate_uuid() function can be used to generate a dummy UUID.

In case you don't know how to interact with the program in Postman, you can interact with its API Docs available at and

The value P3D in process_after is followed the ISO 8601 format. You can find out more details at

https://docs.pydantic.dev/latest/concepts/types/
http://127.0.0.1:8000/docs
http://127.0.0.1:8000/redoc
https://en.wikipedia.org/wiki/ISO_8601#Durations
🍓
Page cover image
Fig. 1. Interact with the API endpoint in Postman