August 11, 2023

How an asyncio Python project with SQLAlchemy and Strawberry can have a great typed DX on the frontend via codegen and React hooks

Modern Python Web Stack

image

SQLAlchemy now has an asyncio extension. Strawberry is a new-ish GraphQL library based on Python dataclasses that makes full use of type hints and mypy extensions. Codegen can generate typed React hooks in TypeScript. This template or reference project shows how all these pieces can be put together for an awesome typed developer experience.

This is a mini version of the Inch tech stack. The schema is monitored by codegen that creates urql TypeScript hooks. The goal was to have strong data consistency between the backend and frontend. Another benefit is a great VS Code environment that highlights any potential errors when communicating with the backend.

Getting started

Install Python and NPM packages

poetry install
npm i

Drop and recreate all database tables

poetry run python models.py

Run the Python GraphQL backend on port :8000 - Next.js will reverse proxy /graphql to here

poetry run uvicorn app:app --reload --host '::'

Start the GraphQL server

npm run codegen --watch

Run the frontend

npm run dev

VS Code

Inside .vscode/settings.json you'll see how to have nice VS Code mypy errors, import sorting and code formatting. Pylance does not yet deal well with declarative type hinted SQLAlchemy models. However there are pretty good SQLA type stubs and a mypy plugin. That's why in the settings you'll see python.analysis.typeCheckingMode switched off and mypy enabled instead.