FastAPI

FastAPI is a popular ASGI web framework. The purpose of this tutorial is to give some hints on how to get started with Piccolo and FastAPI.

Piccolo and FastAPI are a great match, and are commonly used together.

Creating a new project

Using the piccolo asgi new command, Piccolo will scaffold a new FastAPI app for you - simple!

Pydantic models

FastAPI uses Pydantic for serialising and deserialising data.

Piccolo provides create_pydantic_model which creates Pydantic models for you based on your Piccolo tables.

Of course, you can also just define your Pydantic models by hand.

Transactions

Using FastAPI’s dependency injection system, we can easily wrap each endpoint in a transaction.

from fastapi import Depends, FastAPI
from pydantic import BaseModel

from piccolo.columns.column_types import Varchar
from piccolo.engine.sqlite import SQLiteEngine
from piccolo.table import Table

DB = SQLiteEngine()


class Band(Table, db=DB):
    """
    You would usually import this from tables.py
    """

    name = Varchar()


async def transaction():
    async with DB.transaction() as transaction:
        yield transaction


app = FastAPI()


@app.get("/bands/", dependencies=[Depends(transaction)])
async def get_bands():
    return await Band.select()


class CreateBandModel(BaseModel):
    name: str


@app.post("/bands/", dependencies=[Depends(transaction)])
async def create_band(model: CreateBandModel):
    await Band({Band.name: model.name}).save()

    # If an exception is raised then the transaction is rolled back.
    raise Exception("Oops")


async def main():
    await Band.create_table(if_not_exists=True)


if __name__ == "__main__":
    import asyncio

    import uvicorn

    asyncio.run(main())
    uvicorn.run(app)

FastAPI dependencies can be declared at the endpoint, APIRouter, or even app level.

FastAPIWrapper

Piccolo API has a powerful utility called FastAPIWrapper which generates REST endpoints based on your Piccolo tables, and adds them to FastAPI’s Swagger docs. It’s a very productive way of building an API.

Authentication

Piccolo API ships with authentication middleware which is compatible with FastAPI middleware.