Skip to content

Tortoise (async)

When generating routes, the TortoiseCRUDRouter will automatically tie into your database using your Tortoise models. To use it, you must pass a pydantic schema, your Tortoise database model to it, and register Tortoise ORM with your FastAPI App.

Warning

To use the SQLAlchemyCRUDRouter, Tortoise ORM must be first installed.

Simple Example

Below is an example assuming that you have already imported and created all the required models.

app = FastAPI()
register_tortoise(app, config=TORTOISE_ORM)

router = TortoiseCRUDRouter(
    schema=MyPydanticModel, 
    db_model=MyDBModel, 
    prefix="test"
)

app.include_router(router)

You can provide your TORTOISE_ORM from a file or as a dictionary. If you want to provide it as a dictionary, this would be how:

TORTOISE_ORM = {
    "connections": {"default": 'postgres_url_here'},
    "apps": {
        "models": {
            "models": ["example"],
            "default_connection": "default",
        },
    },
}

Where "models": ["example"] represents that example.py is where your Tortoise database ORM models are located. If you ended up having a lot of these, you might want to break it out into a models.py file and thus your config would change to "models": ["models"]. If you use Aerich for database migrations, you'll need to add "aerich.models" to your config.

Note

The create_schema should not include the primary id field as this should be generated by the database. If you don't provide a create_schema, a primary key stripped schema will be made for you.

Full Example

# example.py

import uvicorn as uvicorn
from fastapi import FastAPI
from fastapi_crudrouter.core.tortoise import TortoiseCRUDRouter
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.models import Model
from tortoise import fields, Tortoise

TORTOISE_ORM = {
    "connections": {"default": 'postgres_url'},
    "apps": {
        "models": {
            "models": ["example"],
            "default_connection": "default",
        },
    },
}

# Create Database Tables
async def init():
    await Tortoise.init(config=TORTOISE_ORM)
    await Tortoise.generate_schemas()

app = FastAPI()
register_tortoise(app, config=TORTOISE_ORM)


# Tortoise ORM Model
class TestModel(Model):
    test = fields.IntField(null=False, description=f"Test value")
    ts = fields.IntField(null=False, description=f"Epoch time")


# Pydantic schema
TestSchema = pydantic_model_creator(TestModel, name=f"{TestModel.__name__}Schema")
TestSchemaCreate = pydantic_model_creator(TestModel, name=f"{TestModel.__name__}SchemaCreate", exclude_readonly=True)

# Make your FastAPI Router from your Pydantic schema and Tortoise Model
router = TortoiseCRUDRouter(
    schema=TestSchema,
    create_schema=TestSchemaCreate,
    db_model=TestModel,
    prefix="test"
)

# Add it to your app
app.include_router(router)

if __name__ == "__main__":
    uvicorn.run("example:app", host="127.0.0.1", port=5000, log_level="info")