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.


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

    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

class CreateBandModel(BaseModel):
    name: str"/bands/", dependencies=[Depends(transaction)])
async def create_band(model: CreateBandModel):
    await Band({}).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

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


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.


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