(One of my summaries of the May 2023 Dutch PyGrunn conference).
Ivor works for dacom, a GIS and agri company. They use both django and fastAIP.
FastAPI is a relatively new web framework for building REST APIs. The ingredients are pydantic, data validation based on python type hints, and starlette, an asgi async toolkit.
With pydantic you can define classes/models of your data. With python type hints. Pydantic takes care of the type checking and also converts the input to the correct type. With Django, you’ll get the correct type out of the database, but it won’t automatically fix up the model you’re instantiating yourself.
He showed a simple django app with two models (“Farm” and “Field”). Right next
to it he generated a fastAPI app. In the asgi.py
file he hooked up django
as usual and added a fastAPI app to the router. So django and fastapi run side
by side. He showed the django admin, running as usual, and /api/
with the
fastAPI functionality.
He uses fastapi-utils for a
“DTO”, data transfer object. fastapi-models has an APIModel
class to map
pydantic models to models in some other system. In this case django’s
ORM. Seemed to work like a charm.
But… why would you? You get a consistent API. automatic documentation and validation. Automatic api style and consistent naming. No undocumented attributes.
In 2011 he used tastypie. Is that still maintained? At the time, users would look weirdly at an API: “can’t I use ftp and csv files”? Since 2013 he started using djangorestframework. Nowadays, users ask for the swagger endpoint: they’re used to APIs and want a clean and modern one. The world has changed. FastAPI fits this new world a bit better.
The exposed API should be intuitive. The api should be stable. And useful for front-end teams and third parties. Your database model is not your REST API, so really design your UI and REST API, it is not an afterthought. Make a beautiful and logical API out of it. So a separately defined API is a bit of extra work, but it is worth the effort.
Why not djangorestframework? Well, it is very well integrated with Django. He still uses is for multiple projects. But he is starting to like fastAPI. Another alternative might be Django Ninja, which is inspired by fastAPI. It might become something nice, but is less mature at the moment.
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):