Generating models from Database with FastAPI and SQLAlchemy

I have a Django project running on production with PostgreSQL.

I want to spin a separate FastAPI microservice to do a specific task, and I want it to communicate directly with the database I have hooked up with Django.

I do not want to rewrite all the models in FastAPI using pydantic, and at the same time I don't want to make a mistake.

In Django, there is python inspectdb to automatically generate models using an existing database. Is there an equivalent in FastAPI, SQLAlchemy or Pydantic?

Have a look at sqlacodegen. It's a tool that reads the structure of an existing database and generates the appropriate SQLAlchemy model code.

It currently offeres a variety of built-in different generators:

  • tables (only generates Table objects, for those who don't want to use the ORM)
  • declarative (the default; generates classes inheriting from declarative_base())
  • dataclasses (generates dataclass-based models; v1.4+ only)
  • sqlmodels (generates model classes for SQLModel)

Declarative is the default, and generates standard SQLAlchemy models which you can use in your FastAPI application. You can also explore the sqlmodels generator as SQLModel is designed to simplify interacting with SQL databases in FastAPI applications (and it was created by the same author as FastAPI).

Back to Top